Core Module
12 min forge
C++ Loops & Iteration
Mastering for, while, and do-while loops to handle repetitive tasks.
C++ Loops & Iteration
π What is it
Loops allow you to execute a block of code multiple times. C++ provides for, while, and do-while loops.
β‘ When to use
Use loops to traverse arrays, repeat an operation until a condition is met, or run a continuous process.
π§ Time complexity
- Single loop over $N$ items: $O(N)$
- Nested loops: $O(N^2)$ or higher.
π» Code example
cpp Standard// For loop - traversing an array for (int i = 0; i < 5; i++) { std::cout << i << " "; } // While loop int count = 0; while (count < 5) { count++; }
β Common mistakes
- Infinite loops: Condition never becomes false.
- Off-by-one errors: Starting from 1 instead of 0, or using
<=instead of<. - Forgetting to increment the loop variable inside a
whileloop.