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 while loop.