Control Flow
Control flow is the order in which statements and instructions are executed in a program. In C#, control flow is managed using if statements, switch statements, and loops.
If Statements
If statements are used to execute a block of code only if a certain condition is true. Here's an example:
1int x = 10;
2if (x > 5)
3{
4 Console.WriteLine("x is greater than 5");
5}
In this example, the code inside the if statement will only be executed if the value of x
is greater than 5.
Switch Statements
Switch statements are used to perform different actions based on different conditions. Here's an example:
1string day = "Monday";
2switch (day)
3{
4 case "Monday":
5 Console.WriteLine("It's Monday");
6 break;
7 case "Tuesday":
8 Console.WriteLine("It's Tuesday");
9 break;
10 default:
11 Console.WriteLine("It's another day");
12 break;
13}
In this example, the code will check the value of the day
variable and execute the corresponding block of code.
Loops
Loops are used to repeatedly execute a block of code until a certain condition is met. Here's an example of a for loop:
1for (int i = 0; i < 5; i++)
2{
3 Console.WriteLine("Iteration: " + i);
4}
This loop will execute the code inside the curly braces for each iteration, starting from 0 and incrementing i
by 1 each time, until i
is no longer less than 5.
Understanding control flow is essential in programming as it allows you to control the execution of your code based on different conditions and perform repetitive tasks efficiently.
xxxxxxxxxx
// Example of if statement
int x = 10;
if (x > 5)
{
Console.WriteLine("x is greater than 5");
}
// Example of switch statement
string day = "Monday";
switch (day)
{
case "Monday":
Console.WriteLine("It's Monday");
break;
case "Tuesday":
Console.WriteLine("It's Tuesday");
break;
default:
Console.WriteLine("It's another day");
break;
}
// Example of loop
for (int i = 0; i < 5; i++)
{
Console.WriteLine("Iteration: " + i);
}