🔄 Loops in C: The Magic of Repetition
Imagine you have to write “I love coding” on a paper 100 times. Would you write it manually 100 times? No way! You’d find a smarter way. That’s exactly what loops do in programming!
🎯 The Big Picture
Loops are like a merry-go-round. You get on, go around and around until it’s time to stop. In C programming, loops let your computer repeat tasks without you writing the same code over and over.
Think of it this way:
- Without loops: Write 100 lines to count from 1 to 100
- With loops: Write 3 lines to count from 1 to 100
That’s the power of loops! 🚀
🎠 The Three Merry-Go-Rounds
C gives you three types of loops. Each one is like a different merry-go-round at the park:
| Loop Type | Best For | Check When |
|---|---|---|
for |
When you know exact count | Before riding |
while |
When you don’t know count | Before riding |
do-while |
Must ride at least once | After riding |
1️⃣ The for Loop
🎪 The Story
Imagine you’re at a carnival ticket booth. The sign says: “Rides: Start at ticket 1, stop at ticket 5, use 1 ticket per ride.”
That’s a for loop! You know:
- Where to start (ticket 1)
- When to stop (ticket 5)
- How to move forward (use 1 ticket)
📝 The Recipe
for (start; condition; step) {
// do something
}
🌟 Simple Example
Print “Hello!” 5 times:
#include <stdio.h>
int main() {
for (int i = 1; i <= 5; i++) {
printf("Hello! %d\n", i);
}
return 0;
}
Output:
Hello! 1
Hello! 2
Hello! 3
Hello! 4
Hello! 5
🧩 Breaking It Down
graph TD A[Start: i = 1] --> B{Is i <= 5?} B -->|Yes| C[Print Hello!] C --> D[Add 1 to i] D --> B B -->|No| E[Done! Exit loop]
What happens:
i = 1→ We start at 1i <= 5→ Is 1 less than or equal to 5? YES!- Print “Hello! 1”
i++→ Now i = 2- Repeat until i becomes 6 (then we stop)
2️⃣ The while Loop
🎪 The Story
Imagine you’re eating cookies from a jar. You don’t know how many are inside. You just keep eating while there are cookies left!
While (there are cookies) {
Eat one cookie
}
📝 The Recipe
while (condition) {
// do something
}
🌟 Simple Example
Count down from 5 to 1:
#include <stdio.h>
int main() {
int count = 5;
while (count > 0) {
printf("%d...\n", count);
count--;
}
printf("Blast off! 🚀\n");
return 0;
}
Output:
5...
4...
3...
2...
1...
Blast off! 🚀
🧩 Breaking It Down
graph TD A[count = 5] --> B{Is count > 0?} B -->|Yes| C[Print count] C --> D[Subtract 1 from count] D --> B B -->|No| E[Print Blast off!]
🆚 for vs while
Use for when… |
Use while when… |
|---|---|
| You know exact count | You don’t know count |
| Counting 1 to 10 | Reading until end of file |
| Fixed repetitions | User decides when to stop |
3️⃣ The do-while Loop
🎪 The Story
Imagine a game where you MUST play at least once before deciding to play again.
The game asks: “Play again?” AFTER you finish your first game.
That’s do-while! You do something first, then check if you want to continue.
📝 The Recipe
do {
// do something
} while (condition);
⚠️ Don’t forget the semicolon at the end!
🌟 Simple Example
Ask for a password (must try at least once):
#include <stdio.h>
int main() {
int password;
do {
printf("Enter password: ");
scanf("%d", &password);
} while (password != 1234);
printf("Access granted!\n");
return 0;
}
🧩 The Key Difference
graph TD subgraph while Loop A1[Check condition] --> A2{True?} A2 -->|Yes| A3[Do task] A3 --> A1 A2 -->|No| A4[Exit] end subgraph do-while Loop B1[Do task first] --> B2{Continue?} B2 -->|Yes| B1 B2 -->|No| B3[Exit] end
while |
do-while |
|---|---|
| Might run 0 times | Runs at least 1 time |
| Check THEN do | Do THEN check |
| Entry-controlled | Exit-controlled |
4️⃣ Nested Loops
🎪 The Story
Imagine a clock:
- The hour hand moves slowly (outer loop)
- The minute hand goes full circle for EACH hour (inner loop)
That’s a nested loop! A loop inside a loop.
📝 The Recipe
for (outer) {
for (inner) {
// inner runs completely
// for EACH outer run
}
}
🌟 Simple Example
Print a 3x3 star pattern:
#include <stdio.h>
int main() {
for (int row = 1; row <= 3; row++) {
for (int col = 1; col <= 3; col++) {
printf("* ");
}
printf("\n");
}
return 0;
}
Output:
* * *
* * *
* * *
🧩 How It Works
graph TD A[Row 1 starts] --> B[Print 3 stars] B --> C[New line] C --> D[Row 2 starts] D --> E[Print 3 stars] E --> F[New line] F --> G[Row 3 starts] G --> H[Print 3 stars] H --> I[Done!]
Think of it as:
- Outer loop = Rows (vertical)
- Inner loop = Columns (horizontal)
5️⃣ The break Statement
🎪 The Story
You’re on that merry-go-round, spinning happily. Suddenly, you feel sick! 🤢 You shout “STOP! LET ME OFF!”
That’s break! It immediately exits the loop, no matter what.
📝 The Recipe
while (condition) {
if (emergency) {
break; // EXIT NOW!
}
}
🌟 Simple Example
Find first number divisible by 7:
#include <stdio.h>
int main() {
for (int i = 1; i <= 100; i++) {
if (i % 7 == 0) {
printf("Found: %d\n", i);
break; // Stop searching!
}
}
return 0;
}
Output:
Found: 7
Without break, we’d find 7, 14, 21… all of them!
🧩 Visual
graph TD A[Start loop] --> B{i = 7?} B -->|No| C[Keep searching] C --> A B -->|Yes| D[BREAK!] D --> E[Exit loop immediately]
6️⃣ The continue Statement
🎪 The Story
You’re eating a bowl of grapes. Every time you find a rotten one, you skip it and grab the next grape. You don’t stop eating completely!
That’s continue! It skips THIS round but keeps the loop going.
📝 The Recipe
while (condition) {
if (skip_this_one) {
continue; // Skip to next round
}
// This code is skipped when continue runs
}
🌟 Simple Example
Print 1-10 but skip 5:
#include <stdio.h>
int main() {
for (int i = 1; i <= 10; i++) {
if (i == 5) {
continue; // Skip 5!
}
printf("%d ", i);
}
return 0;
}
Output:
1 2 3 4 5 6 7 8 9 10
Wait, 5 is there? Let me fix:
1 2 3 4 6 7 8 9 10
See? 5 is missing! We skipped it! 🎉
🆚 break vs continue
graph LR subgraph break A1[Loop running] --> A2[break hit] A2 --> A3[EXIT loop completely] end subgraph continue B1[Loop running] --> B2[continue hit] B2 --> B3[Skip to next iteration] B3 --> B1 end
break |
continue |
|---|---|
| “I’m done. Goodbye!” | “Skip this one. Next!” |
| Exits the loop | Skips current round |
| Loop stops forever | Loop continues |
🎯 Quick Reference Table
| Concept | What It Does | When to Use |
|---|---|---|
for |
Known count loop | Counting, arrays |
while |
Unknown count | Reading files, user input |
do-while |
At least once | Menu systems, validation |
| Nested | Loop in loop | Patterns, 2D data |
break |
Exit NOW | Found what you need |
continue |
Skip this one | Filter out items |
🚀 You’ve Got This!
Loops are your superpower for making computers do repetitive work. Remember:
- 🎯 Know your count? → Use
for - ❓ Don’t know count? → Use
while - 🎮 Must run once? → Use
do-while - 🏗️ 2D patterns? → Nest your loops
- 🛑 Emergency exit? → Use
break - ⏭️ Skip one? → Use
continue
Now go make your computer work hard while you relax! 😎