Loops in C++
A comprehensive guide to loops in C++ with real-life examples, use cases, and differences.
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 πΆββοΈ
Similarly, in programming, loops help in running repetitive tasks efficiently.
Types of Loops in C++
for
loopwhile
loopdo-while
loop
Each serves a different purpose. Letβs explore them one by one. π
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
for
loop 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.
Output:
continue
: Skips the current iteration and moves to the next.
Example: Skip number 3.
Output:
Real-Life Analogy:
- break β Leaving a movie theater πΏ when it gets boring.
- continue β Skipping an ad while watching YouTube. π₯
Differences Between Loops
Feature | for Loop | while Loop | do-while Loop |
---|---|---|---|
Used When? | Fixed number of iterations | Unknown number of iterations | At least one execution needed |
Condition Check | Before iteration | Before iteration | After iteration |
Best For? | Counting, iterating over arrays | Waiting for user input | Menus, login attempts |
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
&continue
for controlling loop flow.
Mastering loops is key to writing efficient C++ programs!