C++ Loops โ for, while, do-while & Range-Based for Masterclass
Welcome to Phase 5 (Chapter 5): C++ Loops โ for, while, do-while & Range-Based for Masterclass! Iteration structures execute code repeatedly. In Modern C++, range-based for (const auto &item : collection) provides safe, clean traversal of strings, vectors, and arrays.
| Loop Construct | Syntax | Best Use Case |
|---|---|---|
Standard for | for (int i=0; i<n; i++) | Known iteration count, index access needed |
Range-Based for | for (const auto &x : vec) | Modern traversal of containers without manual index counters |
while | while (condition) | Event-driven iteration where end condition is dynamic |
do-while | do { ... } while(cond); | Guaranteed at least 1 execution (e.g. Menu loops) |
#include <iostream>
#include <vector>
#include <string>
bool isPrime(int n) {
if (n <= 1) return false;
for (int i = 2; i * i <= n; i++) {
if (n % i == 0) return false;
}
return true;
}
int main() {
// 1. Fibonacci Series Generation
int n = 7, t1 = 0, t2 = 1, nextTerm;
std::cout << "Fibonacci Series (7 terms): ";
for (int i = 1; i <= n; ++i) {
std::cout << t1 << " ";
nextTerm = t1 + t2;
t1 = t2;
t2 = nextTerm;
}
std::cout << "\n";
// 2. Prime Number Check
int num = 29;
std::cout << num << " is " << (isPrime(num) ? "PRIME" : "NOT PRIME") << "\n";
// 3. Modern Range-Based For Loop Over Vector
std::vector<std::string> fruits{"Apple", "Banana", "Cherry"};
std::cout << "Fruits: ";
for (const auto &fruit : fruits) {
std::cout << fruit << " ";
}
std::cout << "\n";
return 0;
} Q1: Why pass by const auto & in range-based for loops?
Passing by const auto & avoids making expensive copies of objects while guaranteeing the loop cannot modify elements.
Q2: What happens if you modify a vector inside a range-based for loop?
Adding/removing elements invalidates iterators, leading to Undefined Behavior crashes!
Q3: What is the difference between break and continue?
break exits the loop immediately. continue skips the rest of the current iteration and advances to the next loop step.
Q4: How do nested loops affect Big-O time complexity?
Two nested loops of size N yield O(Nยฒ) quadratic time complexity. Avoid deep nesting for large datasets.
Q5: Can do-while loops be infinite?
Yes, if the condition expression remains true continuously (e.g. `do { ... } while(true);`).