C++ tutorials  /  Loops in C++ (for, while, do-while)
Chapter 5 · C++

Loops in C++ (for, while, do-while)

A loop in C++ is a control structure that repeatedly executes a block of code as long as a specified condition remains true, allowing a program to perform repetitive tasks efficiently without duplicating code. C++ provides three primary loop constructs — 'for', 'while', and 'do-while' — each suited to different scenarios depending on whether the number of iterations is known in advance and whether the loop body must execute at least once.

Imagine washing 50 dishes one by one — instead of writing 'wash dish' 50 separate times, you'd just say 'keep washing dishes until there are none left.' That's exactly what a loop does in code: it repeats an action until a condition is no longer true, saving you from writing the same instructions over and over. A 'for' loop is best when you know exactly how many times to repeat something (like counting 1 to 10), a 'while' loop is best when you don't know the exact count but know the stopping condition (like reading input until the user types 'quit'), and a 'do-while' loop guarantees the code runs at least once before checking the condition.

Instagram's infinite scroll feed uses loop-like logic to keep fetching and displaying new posts as long as the user keeps scrolling (a while-like condition). A point-of-sale system at a grocery store uses a for loop to iterate through every item in a shopping cart to calculate the total bill. A password login prompt commonly uses a do-while loop, since the user must be asked for their password at least once before the program checks if it's correct, then loops again only if it's wrong. Video games use loops extensively in their 'game loop' — a continuously running while loop that keeps updating the screen, checking input, and rendering graphics 60+ times per second until the player exits the game.

Without loops, performing any repetitive task — processing every item in a list, validating user input until it's correct, or running a simulation for thousands of steps — would require manually writing out the same code again and again, which is impractical, error-prone, and impossible for tasks with a variable or very large number of repetitions. Loops let programs handle repetition dynamically and efficiently, forming the foundation of algorithms that process arrays, search data, sort collections, and run continuously (like game engines and servers).

  • for Loop: Ideal when the number of iterations is known beforehand; combines initialization, condition-checking, and increment/decrement into a single compact line, commonly used for iterating a fixed number of times or traversing arrays and containers by index.
  • while Loop: Checks its condition before each iteration (entry-controlled loop), executing the loop body only as long as the condition remains true; used when the number of iterations isn't known in advance and depends on dynamic runtime conditions.
  • do-while Loop: Checks its condition after executing the loop body (exit-controlled loop), guaranteeing the code runs at least once regardless of the condition; commonly used for input validation and menu-driven programs where the action must happen before checking whether to repeat.
  • Range-Based for Loop (C++11+): A modern, simplified for-loop syntax introduced in C++11 that directly iterates over each element of a container (like an array or vector) without needing explicit index management, improving readability and reducing off-by-one errors.
  • Nested Loops: A loop placed inside another loop, where the inner loop completes all of its iterations for each single iteration of the outer loop; commonly used for working with 2D data structures like matrices or grids, and for generating patterns.
// for loop for (initialization; condition; update) { // code to repeat } // while loop while (condition) { // code to repeat } // do-while loop do { // code to repeat } while (condition); // range-based for loop (C++11+) for (dataType element : container) { // use element }
A developer needs to build a simple number-guessing game that repeatedly prompts the user for a guess until they enter the correct number (requiring a loop that runs at least once), and also needs to print a multiplication table for a given number from 1 to 10 (requiring a loop with a known, fixed number of iterations).
Printing a Multiplication Table Using a for Loop
Demonstrates a classic for loop use case: repeating an action a known, fixed number of times.
cpp
#include <iostream> using namespace std; int main() { int num = 5; for (int i = 1; i <= 10; i++) { cout << num << " x " << i << " = " << (num * i) << endl; } return 0; }
5 x 1 = 5 5 x 2 = 10 5 x 3 = 15 5 x 4 = 20 5 x 5 = 25 5 x 6 = 30 5 x 7 = 35 5 x 8 = 40 5 x 9 = 45 5 x 10 = 50
The for loop initializes 'i' to 1, checks the condition 'i <= 10' before each iteration, executes the multiplication and print statement, then increments 'i' by 1 after each pass. This continues until 'i' exceeds 10, at which point the condition becomes false and the loop terminates.
Input Validation Using a do-while Loop
Shows a do-while loop guaranteeing the prompt runs at least once, repeating only if the entered value is invalid.
cpp
#include <iostream> using namespace std; int main() { int age; do { cout << "Enter your age (must be positive): "; cin >> age; if (age <= 0) { cout << "Invalid input, try again." << endl; } } while (age <= 0); cout << "Age accepted: " << age << endl; return 0; }
Enter your age (must be positive): -5 Invalid input, try again. Enter your age (must be positive): 25 Age accepted: 25
Because it's a do-while loop, the prompt executes at least once before the condition 'age <= 0' is ever checked. If the user enters an invalid value like -5, the loop body repeats, asking again — this pattern guarantees at least one attempt while still allowing repeated retries until valid input is given.
  • Creating an Infinite Loop by Forgetting to Update the Condition Variable: Writing 'while (i < 10) { cout << i; }' without incrementing 'i' inside the loop body causes the condition to remain true forever, freezing or crashing the program. Always ensure the loop's controlling variable is modified somewhere inside the loop body so the condition can eventually become false.
  • Off-by-One Errors in Loop Boundaries: Using '<=' when '<' was intended (or vice versa) causes a loop to execute one time too many or too few — for example, 'for (int i = 0; i <= arraySize; i++)' accessing 'array[i]' will go one index past the array's valid bounds when 'i' equals 'arraySize', causing undefined behavior or a crash.
  • Using a for Loop When a while Loop Is More Appropriate (or Vice Versa): Forcing a for loop's compact syntax onto a situation where the number of iterations is genuinely unknown (like reading input until a sentinel value) leads to awkward, hard-to-read code with an empty condition or update clause. Choose the loop type that naturally matches whether the iteration count is known in advance.
  • Modifying the Loop Control Variable Inside the Loop Body Unexpectedly: Manually changing the value of the loop counter inside a for loop's body (in addition to its automatic update) can cause the loop to skip iterations, repeat unexpectedly, or run for an incorrect number of cycles, making the code's behavior confusing and error-prone for anyone reading it later.
  • Forgetting the Semicolon After a do-while Loop's Condition: Unlike for and while loops, a do-while loop's closing 'while (condition)' must be followed by a semicolon ';' — omitting it is a common syntax error for developers switching between loop types, since it's easy to forget this one structural difference.
  • Choose the Loop Type That Matches the Problem's Natural Structure: Use a 'for' loop when the iteration count is known in advance (like iterating a fixed range or array), a 'while' loop when the stopping condition is dynamic and unknown ahead of time, and a 'do-while' loop specifically when the body must execute at least once regardless of the condition (like input prompts).
  • Prefer Range-Based for Loops When Simply Iterating Over a Container: When you just need to access each element of an array, vector, or other container without needing the index itself, use 'for (auto& element : container)' instead of manual index-based loops — it's more readable, less error-prone (no off-by-one risk), and clearly communicates intent.
  • Always Ensure the Loop Has a Clear, Reachable Exit Condition: Before writing a loop, mentally trace through how the controlling condition will eventually become false. For while/do-while loops especially, double-check that every code path inside the loop body properly updates the condition variable to avoid accidental infinite loops.
  • Use break and continue Judiciously, Not as a Crutch for Poor Loop Design: 'break' (exits the loop entirely) and 'continue' (skips to the next iteration) are useful for handling exceptional cases within a loop, but overusing them to patch overly complex loop conditions can make code harder to follow — consider restructuring the loop's condition or logic first if you find yourself relying on many scattered break/continue statements.
What is the key difference between a while loop and a do-while loop?
A while loop is entry-controlled, meaning it checks the condition before executing the loop body — if the condition is false from the start, the body never executes even once. A do-while loop is exit-controlled, meaning it executes the loop body first and checks the condition afterward, guaranteeing the body runs at least once regardless of whether the condition is initially true or false.
What causes an infinite loop, and how would you identify and fix one in existing code?
An infinite loop occurs when the loop's controlling condition never becomes false, typically because the variable(s) it depends on are never updated inside the loop body, or the update logic never actually causes the condition to change to false (e.g., incrementing in the wrong direction). To identify one, trace through the loop's condition and confirm that every code path correctly modifies the relevant variable(s) toward the exit condition; the fix usually involves correcting the increment/decrement logic or adding a proper break condition.
What is the difference between 'break' and 'continue' statements in loops?
'break' immediately terminates the entire loop, transferring control to the first statement after the loop, regardless of how many iterations remain. 'continue' skips only the rest of the current iteration's code and jumps directly to the loop's next condition check (or update step in a for loop), allowing the loop to keep running for subsequent iterations.
How does a range-based for loop work internally in C++, and what are its limitations?
A range-based for loop, introduced in C++11, is syntactic sugar that internally uses the container's begin() and end() iterators to traverse each element, automatically handling iterator increment and dereferencing behind the scenes. Its main limitation is that, in its basic form, it doesn't provide direct access to the element's index, so if you need the index during iteration (e.g., for printing 'element at position 3'), you either need a traditional index-based for loop or must manually track a separate counter variable alongside the range-based loop.
In a nested loop, how does 'break' behave, and how can you exit multiple nested loops at once?
A 'break' statement inside a nested loop only exits the innermost loop it's directly contained within — it does not affect any outer loops, which continue executing normally. To exit multiple nested loops at once, common approaches include using a boolean 'flag' variable checked in the outer loop's condition, restructuring the logic into a separate function and using a 'return' statement, or in some cases using a 'goto' statement (though this is generally discouraged in modern C++ for readability reasons).
Write a C++ program using a for loop to calculate and print the factorial of a given number.
#include <iostream> using namespace std; int main() { int n = 6; long long factorial = 1; for (int i = 1; i <= n; i++) { factorial *= i; } cout << "Factorial of " << n << " is " << factorial << endl; return 0; }
Write a program using nested for loops to print a right-angled triangle pattern of stars ('*') with 5 rows.
#include <iostream> using namespace std; int main() { int rows = 5; for (int i = 1; i <= rows; i++) { for (int j = 1; j <= i; j++) { cout << "* "; } cout << endl; } return 0; }
Predict the output and identify the bug in this code: int i = 0; while (i < 5) { cout << i << " "; }
This code causes an infinite loop and will keep printing '0 0 0 0 0 ...' forever (or until the program is manually terminated/crashes). The bug is that 'i' is never incremented inside the loop body, so the condition 'i < 5' remains true indefinitely. The fix is to add 'i++;' inside the loop body, e.g., 'while (i < 5) { cout << i << " "; i++; }', which would correctly print '0 1 2 3 4' and then terminate.

Loops — for, while, and do-while — allow C++ programs to repeat blocks of code efficiently without duplicating instructions, forming the foundation for processing collections, validating input, and building responsive, repetitive systems like game loops and menu-driven applications. Choosing the correct loop type based on whether the iteration count is known in advance (for) or depends on a dynamic condition (while/do-while), while carefully avoiding classic pitfalls like infinite loops and off-by-one errors, is a core skill every C++ programmer must master before moving on to arrays, functions, and more advanced algorithms.

© 2026 CompileX. Maintained by Aditya Kumar Sharma.