🚦 Program Flow: Control Flow in C#
The Traffic Controller Inside Your Code
Imagine you’re a traffic controller at a busy intersection. Cars are coming from all directions, and YOUR job is to decide:
- Which cars go now?
- Which cars wait?
- Which cars go around in circles until something happens?
That’s EXACTLY what Control Flow does in C#! It’s the traffic controller that tells your code which path to take.
🎯 What You’ll Master
graph TD A[Control Flow] --> B[If-Else] A --> C[Switch] A --> D[Loops] A --> E[Loop Control] B --> B1[Make Decisions] C --> C1[Choose One Path] D --> D1[Repeat Actions] E --> E1[Control Repetition]
🔀 If-Else Statements
The “Yes or No” Decision Maker
Think of if-else like asking a simple question: “Is this true?”
If YES → Do this thing If NO → Do that other thing
The Basic Pattern
int age = 10;
if (age >= 18)
{
Console.WriteLine("You can vote!");
}
else
{
Console.WriteLine("Too young to vote.");
}
Output: Too young to vote.
Because 10 is NOT greater than or equal to 18, we go to the else path!
🎂 Real Life Example: Birthday Cake
int cakeSlices = 3;
int guests = 5;
if (cakeSlices >= guests)
{
Console.WriteLine("Everyone gets cake!");
}
else
{
Console.WriteLine("We need more cake!");
}
Output: We need more cake!
3 slices for 5 guests? Not enough!
🪜 What If There Are MORE Options? (Else-If)
Sometimes it’s not just yes/no. It’s multiple choices!
Think of a slide at the playground:
- Too short? → Can’t go on the big slide
- Just right? → Use the medium slide
- Tall enough? → Use the big slide!
int height = 120; // centimeters
if (height < 100)
{
Console.WriteLine("Small slide for you!");
}
else if (height < 140)
{
Console.WriteLine("Medium slide - perfect!");
}
else
{
Console.WriteLine("Big slide! Wheee!");
}
Output: Medium slide - perfect!
The code checks top to bottom. First true condition wins!
🧩 Nested If: Decisions Inside Decisions
Sometimes you need to ask MORE questions after the first one.
bool hasTicket = true;
int age = 8;
if (hasTicket)
{
if (age >= 10)
{
Console.WriteLine("Enjoy the roller coaster!");
}
else
{
Console.WriteLine("Try the kids' ride!");
}
}
else
{
Console.WriteLine("Buy a ticket first!");
}
Output: Try the kids' ride!
First we check the ticket. THEN we check the age!
🎚️ Switch Statements
The Multiple Choice Champion
Imagine a vending machine. You press:
- Button 1 → Chips
- Button 2 → Candy
- Button 3 → Soda
- Button 4 → Cookie
That’s a switch statement! One input, multiple possible outputs.
The Basic Pattern
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("Another day");
break;
}
Output: Wednesday
The break is super important! It says “STOP here, don’t keep going!”
🍕 Pizza Topping Example
string choice = "B";
switch (choice)
{
case "A":
Console.WriteLine("Pepperoni Pizza!");
break;
case "B":
Console.WriteLine("Cheese Pizza!");
break;
case "C":
Console.WriteLine("Veggie Pizza!");
break;
default:
Console.WriteLine("Invalid choice!");
break;
}
Output: Cheese Pizza!
🎨 Multiple Cases, Same Result
What if pressing 1 OR 2 should do the same thing?
char grade = 'A';
switch (grade)
{
case 'A':
case 'B':
Console.WriteLine("Great job!");
break;
case 'C':
Console.WriteLine("Good effort!");
break;
case 'D':
case 'F':
Console.WriteLine("Keep trying!");
break;
default:
Console.WriteLine("Unknown grade");
break;
}
Output: Great job!
Both ‘A’ and ‘B’ fall into the same action!
🔄 Loops
The “Do It Again” Machines
Imagine you’re bouncing a ball. You don’t just bounce ONCE. You bounce again and again and again!
Loops let your code repeat actions without writing the same thing 100 times.
🔢 For Loop: “Do This EXACTLY N Times”
Use for when you KNOW how many times to repeat.
The Basic Pattern
for (int i = 1; i <= 5; i++)
{
Console.WriteLine("Bounce " + i);
}
Output:
Bounce 1
Bounce 2
Bounce 3
Bounce 4
Bounce 5
Breaking It Down:
graph TD A["int i = 1"] --> B["i <= 5 ?"] B -->|YES| C["Run the code"] C --> D["i++"] D --> B B -->|NO| E["EXIT loop"]
| Part | Meaning |
|---|---|
int i = 1 |
Start counting at 1 |
i <= 5 |
Keep going while i is ≤ 5 |
i++ |
Add 1 after each round |
🌟 Star Pattern Example
for (int i = 1; i <= 4; i++)
{
for (int j = 1; j <= i; j++)
{
Console.Write("*");
}
Console.WriteLine();
}
Output:
*
**
***
****
Nested loops = loops inside loops!
🔁 While Loop: “Keep Going UNTIL…”
Use while when you DON’T know exactly how many times.
Think of it like: “Keep eating cookies UNTIL the jar is empty.”
int cookies = 5;
while (cookies > 0)
{
Console.WriteLine("Yum! Cookies left: " + cookies);
cookies--;
}
Console.WriteLine("No more cookies!");
Output:
Yum! Cookies left: 5
Yum! Cookies left: 4
Yum! Cookies left: 3
Yum! Cookies left: 2
Yum! Cookies left: 1
No more cookies!
⚠️ Careful: Infinite Loop!
// DON'T DO THIS!
while (true)
{
Console.WriteLine("Forever...");
}
This runs FOREVER and crashes your program!
Always make sure your loop can end!
🎯 Do-While Loop: “Do Once, Then Check”
The do-while loop ALWAYS runs at least ONCE.
It’s like: “Jump in the pool FIRST, then check if the water is cold.”
int number;
do
{
Console.WriteLine("Enter a positive number:");
number = int.Parse(Console.ReadLine());
} while (number <= 0);
Console.WriteLine("You entered: " + number);
Even if the user enters a positive number immediately, the code runs once!
While vs Do-While
| While | Do-While |
|---|---|
| Checks FIRST | Does FIRST |
| Might run 0 times | Runs at least ONCE |
while(x) {...} |
do {...} while(x); |
📦 Foreach Loop: “For Each Item In…”
Perfect for going through a collection of items!
string[] fruits = {"Apple", "Banana", "Cherry"};
foreach (string fruit in fruits)
{
Console.WriteLine("I love " + fruit);
}
Output:
I love Apple
I love Banana
I love Cherry
No counting needed! It automatically visits EACH item.
🎮 Loop Control Statements
The Emergency Buttons
Sometimes you need to stop early or skip ahead!
🛑 Break: “STOP! Exit Now!”
break immediately exits the loop. Game over!
for (int i = 1; i <= 10; i++)
{
if (i == 5)
{
Console.WriteLine("Found it! Stopping.");
break;
}
Console.WriteLine("Searching... " + i);
}
Output:
Searching... 1
Searching... 2
Searching... 3
Searching... 4
Found it! Stopping.
We never reach 6, 7, 8, 9, 10!
⏭️ Continue: “Skip This One!”
continue skips the current round and jumps to the next.
for (int i = 1; i <= 5; i++)
{
if (i == 3)
{
continue; // Skip number 3
}
Console.WriteLine("Number: " + i);
}
Output:
Number: 1
Number: 2
Number: 4
Number: 5
Number 3 is SKIPPED!
🏷️ Break vs Continue
graph LR A[Loop Running] --> B{Special Case?} B -->|break| C[EXIT Loop Completely] B -->|continue| D[Skip to Next Round] B -->|neither| E[Normal Execution]
| Command | What It Does |
|---|---|
break |
EXITS the entire loop |
continue |
SKIPS current iteration |
🎯 Practical Example: Number Filter
Let’s find numbers divisible by 3, but stop if we hit 15:
for (int i = 1; i <= 20; i++)
{
if (i == 15)
{
Console.WriteLine("Reached 15! Stopping.");
break;
}
if (i % 3 != 0)
{
continue; // Skip non-divisible
}
Console.WriteLine(i + " is divisible by 3");
}
Output:
3 is divisible by 3
6 is divisible by 3
9 is divisible by 3
12 is divisible by 3
Reached 15! Stopping.
🎊 You Did It!
You’ve mastered the Traffic Controller of C#!
graph TD A[🏆 Control Flow Master] --> B[If-Else: Make Decisions] A --> C[Switch: Choose Paths] A --> D[Loops: Repeat Actions] A --> E[Break/Continue: Control Flow]
Quick Recap
| Tool | Use When… |
|---|---|
| if-else | Yes/No decisions |
| else if | Multiple conditions |
| switch | One variable, many options |
| for | Known number of repeats |
| while | Repeat until condition fails |
| do-while | Run at least once |
| foreach | Go through collections |
| break | Stop loop immediately |
| continue | Skip to next iteration |
Now YOUR code can make smart decisions and repeat actions like a pro! 🚀