How to make use of control flow statements if-else, switch-case, for, while, do-while with help of C#?
In case of C#, control flow statements are very similar to the Java. Here is a way to make their uses in C# through syntaxes and examples.
1. if-else Statement
The if-else statement can be utilized when you want to do some code depending upon a condition whether an expression becomes true or false.
Syntax:
if (condition)
{
// Code to execute if condition is true
} else
// Code to run if the condition is not true
}
Example
int number = 10;
if (number > 0)
{
Console.WriteLine("Positive number");
} else {
Console.WriteLine("Non-positive number");
}
2. switch-case Statement
The switch-case statement lets you execute code based on the value of a variable, and every case corresponds to an acceptable value.
Syntax
switch (variable)
{
case value1:
// Code to run if variable == value1
break;
case value2:
// Code to run if variable == value2
break;
// Other cases
default:
// Code to execute if no case matches
break;
Example:
int day = 3;
switch (day) {
case 1:
Console.WriteLine("Monday");
break;
case 2:
Console.WriteLine("Tuesday");
break;
case 3:
Console.WriteLine("Wednesday");
break;
default:
Console.WriteLine("Invalid day");
break;
}
3. for Loop
The for loop is used when you know in advance how many times to repeat the code.
Syntax:
for (initialization; condition; update) {
// Code to execute repeatedly
}
Example:
for (int i = 0; i < 5; i++) {
Console.WriteLine("Iteration " + i);
}
4. while Loop
The while loop runs a block of code so long as a condition remains true. It is employed when the number of times the code needs to be repeated is unknown and depends upon the condition.
Syntax:
while (condition) {
// Code to repeat
}
Example:
int i = 0;
while (i < 5) {
Console.WriteLine("Iteration " + i);
i++;
}
5. do-while Loop
Do-while loop: It's like while, but the loop will execute at least once before checking the condition.
Syntax:
```
do {
//Code to repeat
} while (condition);
```
Example
``` int i = 0;
do {
Console.WriteLine("Iteration " + i);
i++;
} while (i < 5);.
for: Loops known number of times.
while: Loops while some condition is met, but may never actually execute the code inside the loop.
do-while: Loops at least once, and then checks the condition.
These statements allow flexible control over the execution of code in a C# program.