Introduction
Loops allow us to execute a block of code multiple times. In real life, we often repeat tasks:- Brushing teeth every morning 🪥
- Checking messages repeatedly 📱
- Counting steps while walking 🚶♂️
Types of Loops in C++
forloopwhileloopdo-whileloop
1️⃣ for Loop
The for loop is used when we know how many times the loop should run.
Syntax:
Example: Counting from 1 to 5
Real-Life Analogy:
- Imagine setting an alarm to ring 5 times. ⏰
- The
forloop ensures it rings exactly 5 times.
When to Use for Loop?
✅ When the number of iterations is known in advance.
2️⃣ while Loop
The while loop is used when we don’t know how many times it should run but have a stopping condition.
Syntax:
Example: User enters a number until they type 0
Real-Life Analogy:
- Waiting at a traffic signal 🚦: You stop only when the light turns green.
- The loop keeps running until a stopping condition is met.
When to Use while Loop?
✅ When the number of iterations is unknown and depends on a condition.
3️⃣ do-while Loop
The do-while loop is similar to while, but it ensures the loop runs at least once.
Syntax:
Example: Ask for a password until correct
Real-Life Analogy:
- Asking for Wi-Fi password until you enter the correct one. 📶
When to Use do-while Loop?
✅ When you must run the loop at least once, regardless of conditions.
break and continue in Loops ⚡
break: Exits the loop immediately.
Example: Stop counting at 3.
continue: Skips the current iteration and moves to the next.
Example: Skip number 3.
Real-Life Analogy:
- break → Leaving a movie theater 🍿 when it gets boring.
- continue → Skipping an ad while watching YouTube. 🎥
Differences Between Loops
Conclusion
Loops make programs efficient by handling repetition automatically. We explored:for→ When the number of iterations is known.while→ When iterations depend on a condition.do-while→ When at least one execution is required.break&continuefor controlling loop flow.