Control flow lets your program decide what to do next, or repeat actions.
🤔 Conditional Statements
If/Else:
1
2
3
4
5
if (score >= 60) {
Console.WriteLine("Passed!");
} else {
Console.WriteLine("Try again!");
}
Else If:
1
2
3
4
5
6
7
if (n > 0) {
Console.WriteLine("Positive");
} else if (n < 0) {
Console.WriteLine("Negative");
} else {
Console.WriteLine("Zero");
}
Switch:
1
2
3
4
5
6
7
8
9
10
11
12
string day = "Monday";
switch (day) {
case "Monday":
Console.WriteLine("Start of the week");
break;
case "Friday":
Console.WriteLine("Almost weekend!");
break;
default:
Console.WriteLine("Just another day");
break;
}
🔁 Loops
Looping lets you repeat actions.
While loop:
1
2
3
4
5
int i = 1;
while (i <= 5) {
Console.WriteLine(i);
i++;
}
For loop:
1
2
3
for (int j = 0; j < 3; j++) {
Console.WriteLine($"Loop {j}");
}
Foreach loop (for collections):
1
2
3
4
string[] fruits = {"Apple", "Banana", "Cherry"};
foreach (var fruit in fruits) {
Console.WriteLine(fruit);
}
💡 Try It!
Write a loop that counts down from 5 to 1:
1
2
3
for (int k = 5; k > 0; k--) {
Console.WriteLine(k);
}
Next: Dive deeper into conditional statements.