Loops & Iteration in C++ (for, while, do-while, Range-based for)
๐ข Beginner
๐ Definition
Loops allow a block of C++ statements to execute repeatedly as long as a specified condition remains true. C++ supports four primary loop structures:
forLoop: Best when the number of iterations is known in advance.whileLoop: Best when iterating based on a condition until it becomes false.do-whileLoop: Guarantees execution at least once before checking the condition.- Range-based
forLoop (C++11): Cleanly iterates over containers likestd::vectorand arrays.
๐ฎ๐ณ Hindi Explanation
Loop ka use ek hi code block ko baar-baar repeat karne ke liye hota hai.
forloop tab use hota hai jab pata ho ki loop kitni baar chalana hai (e.g. 1 se 10 tak).whileloop pehle condition check karta hai, fir andar ka code chalata hai.do-whileloop kam se kam ek baar zaroor chalta hai, chahe condition shuru mein hi false ho.- Range-based
forloop C++11 ka modern feature hai jo array ya vector ke har element par aasani se iterate karta hai.
๐ฉ Marathi Explanation
Loop mule aapan ekapeksha jast vela ekach code block punha punha run karu shakto.
forloop: Iteration chi sankhya mahit aslyas.whileloop: Condition true ahe tovar.do-whileloop: Shart (condition) magun tapasli jate, mhanun ha loop kamit kami eka vela nakkich chaltos.- Range-based
for(C++11): Vector kiwa array madhil sarva elements varun iterate karnyasathi.
๐ Syntax Comparison
// 1. Standard for Loop
for (int i = 0; i < 5; i++) { /* Statements */ }
// 2. while Loop
int j = 0;
while (j < 5) { /* Statements */ j++; }
// 3. do-while Loop
int k = 0;
do { /* Statements */ k++; } while (k < 5);
// 4. Range-based for Loop (C++11)
int numbers[] = {10, 20, 30};
for (int val : numbers) { /* Statements */ }
๐ก Practical Example
#include <iostream>
#include <vector>
int main() {
// 1. Standard for Loop
std::cout << "--- 1. STANDARD FOR LOOP (1 to 5) ---" << std::endl;
for (int i = 1; i <= 5; i++) {
std::cout << "Iteration Count: " << i << std::endl;
}
// 2. while Loop (Countdown)
std::cout << "\n--- 2. WHILE LOOP (Countdown) ---" << std::endl;
int count = 3;
while (count > 0) {
std::cout << "Countdown: " << count << "..." << std::endl;
count--;
}
std::cout << "Blastoff! ๐" << std::endl;
// 3. do-while Loop (Guaranteed At Least 1 Run)
std::cout << "\n--- 3. DO-WHILE LOOP ---" << std::endl;
int choice = 0;
do {
std::cout << "Executed choice = " << choice << " (Condition checked after execution)" << std::endl;
choice++;
} while (choice < 1);
// 4. Range-based for Loop (C++11)
std::cout << "\n--- 4. RANGE-BASED FOR LOOP ---" << std::endl;
std::vector<std::string> fruits = {"Apple", "Banana", "Cherry", "Mango"};
for (const std::string& fruit : fruits) {
std::cout << "Fruit Item: " << fruit << std::endl;
}
return 0;
}
๐ Code Breakdown
for (int i = 1; i <= 5; i++): Initializesi = 1, checksi <= 5, runs body, then incrementsi++.const std::string& fruit: Range-based for loop uses aconstreference (&) to avoid copying strings in memory during iteration.
๐ Output
--- 1. STANDARD FOR LOOP (1 to 5) ---
Iteration Count: 1
Iteration Count: 2
Iteration Count: 3
Iteration Count: 4
Iteration Count: 5
--- 2. WHILE LOOP (Countdown) ---
Countdown: 3...
Countdown: 2...
Countdown: 1...
Blastoff! ๐
--- 3. DO-WHILE LOOP ---
Executed choice = 0 (Condition checked after execution)
--- 4. RANGE-BASED FOR LOOP ---
Fruit Item: Apple
Fruit Item: Banana
Fruit Item: Cherry
Fruit Item: Mango
โ ๏ธ Common Mistakes & Infinite Loops
- Infinite Loop Bug: Forgetting to update loop variables (
count--ori++) causes the condition to remaintrueforever, freezing terminal execution! - Off-By-One Errors: Writing
i <= 5wheni < 5was intended, leading to 1 extra iteration. - Modifying Range-based
forTargets Without Reference: Writingfor (int x : vec) x *= 2;modifies the local copyx, NOT the vector elements! Writefor (int& x : vec) x *= 2;(with reference&) to modify vector elements directly.
๐ก๏ธ Best Practices
- Prefer Range-based
forloops when reading or modifying C++ containers likestd::vector. - Use
breakto exit loops early andcontinueto skip the remainder of the current iteration.
๐งช Try It Yourself
- Print all Even numbers between 1 and 20 using a
forloop. - Calculate the factorial of 5 ($5! = 5 \times 4 \times 3 \times 2 \times 1 = 120$) using a
whileloop.
๐ฏ Mini Challenge
Write a program that uses a loop to prompt the user to guess a secret passcode number (e.g. 1234). Keep looping until the user enters the correct passcode!
๐ Related Topics
๐งญ Navigation
| โ C++ Home | โ Previous: Conditionals | Next: Functions โ |