Difficulty: Beginner to Intermediate | Prerequisites: C++ variables, data types, basic operators, conditional statements (if/else).
C++ gives you three loop structures (while, do-while, for) for repeating code, plus increment/decrement operators to control how counters change. Choosing the right loop depends on whether you know the number of iterations in advance and whether the body must run at least once. Mastering loop control variables, sentinel values, and nested loops is essential for processing data, building patterns, and reading/writing files.
Increment operator (++)
A unary operator that increases its operand by one. Can be used in prefix (++x) or postfix (x++) form.
In simple terms, this means: it adds 1 to a variable, but when the adding happens within an expression depends on whether you put the ++ before or after the variable name.
Decrement operator (--)
A unary operator that decreases its operand by one. Also supports prefix (--x) and postfix (x--) forms.
Think of it as: the mirror image of ++, subtracting 1 instead of adding it.
Prefix form (++x / --x)
The variable is incremented or decremented first, then the updated value is used in the surrounding expression.
In simple terms, this means: change the value, then use it.
Postfix form (x++ / x--)
The current value of the variable is used in the expression first, then the variable is incremented or decremented.
In simple terms, this means: use the value, then change it.
Lvalue
An expression that refers to a memory location, typically a variable. The increment and decrement operators require their operand to be an lvalue.
Think of it as: something that can sit on the left side of an assignment. A literal like 5 is not an lvalue; a variable like x is.
While loop
A pre-test loop that evaluates its condition before each iteration. If the condition is false from the start, the body never executes.
Think of it as: "keep going as long as this is true, but check first."
Do-while loop
A post-test loop that executes the body first, then evaluates the condition. Guarantees at least one execution of the loop body.
Think of it as: "do the thing, then decide whether to do it again."
For loop
A compact loop construct that combines initialisation, condition testing, and update into a single header. Ideal for definite iteration where the number of repetitions is known beforehand.
In simple terms, this means: a tidier way to write a counting loop, with all the control in one line.
Counter variable
A variable that tracks how many times a loop has iterated.
Think of it as: a tally that goes up (or down) by one each time through the loop.
Accumulator variable
A variable that keeps a running total by adding each new data value to itself during each iteration.
Think of it as: a running sum. You start at zero and keep adding.
Sentinel value
A special value used to signal the end of data input, allowing a loop to terminate when the number of items is not known in advance.
Think of it as: a stop signal. When the user enters -1 (or whatever the chosen sentinel is), the loop knows there is no more data.
Nested loop
A loop placed inside another loop. The inner loop completes all its iterations for each single iteration of the outer loop.
In simple terms, this means: for every one step of the outer loop, the inner loop runs its full cycle.
Break statement
A control statement that exits the innermost enclosing loop immediately, regardless of the loop condition.
Think of it as: an emergency exit from the loop.
The ++ and -- operators modify their operand by one and require the operand to be an lvalue (a variable)
Prefix (++x / --x): changes the value first, then uses the updated value in the expression
Postfix (x++ / x--): uses the current value in the expression first, then changes the variable
Commonly used in loop update expressions and anywhere a value needs a quick adjustment
Example walkthrough:
int num = 8;
cout << --num; outputs 7 (num decremented to 7 before output)
cout << num++; outputs 7 (current value used first, then num becomes 8)
cout << num; outputs 8
A pre-test loop: the condition is evaluated before each iteration
If the condition is false initially, the body runs zero times
Structure:
while (condition) {
// statements
}The condition must eventually become false, or the loop runs forever (infinite loop)
The body can contain multiple statements enclosed in braces {}
Example:
int count = 0;
while (count < 5) {
cout << count << endl;
count++;
}This prints 0 through 4, then stops when count reaches 5.
The do-while loop is a post-test loop: it executes the body first, then checks the condition
Guarantees the body runs at least once, even if the condition is false from the start
Structure:
do {
// statements
} while (condition);Use do-while when the loop body must execute at least once (e.g. displaying a menu and waiting for valid input)
Use while when it is possible the loop should not run at all
A compact loop best suited for definite iteration (when you know how many times to repeat)
Three expressions in the header: initialisation, test condition, update
Structure:
for (initialisation; condition; update) {
// statements
}Initialisation: runs once at the start
Condition: checked before each iteration; if false, the loop ends
Update: runs after each iteration, typically incrementing or decrementing the loop control variable
The initialisation can be omitted if the variable is declared elsewhere
Example:
for (int i = 0; i < 10; i++) {
cout << i << endl;
}Counters track how many iterations have occurred
Accumulators maintain a running total across iterations
Loop control variables are typically integers, incremented or decremented each cycle
Example of an accumulator:
int total = 0;
for (int i = 1; i <= 10; i++) {
total += i; // sum of 1 to 10
}A sentinel is a specific value chosen to signal "no more data"
The sentinel itself is never processed as valid data
Commonly paired with a while loop and a priming read (reading input once before the loop begins)
Example:
int data;
cout << "Enter data (-1 to stop): ";
cin >> data;
while (data != -1) {
// process data
cin >> data;
}When one loop sits inside another, the inner loop completes all its iterations for each single iteration of the outer loop
Total iterations = outer iterations x inner iterations
Useful for working with multidimensional data such as matrices, grids, and tables
Example (prints a 3-row, 4-column grid of asterisks):
for (int row = 1; row <= 3; row++) {
for (int col = 1; col <= 4; col++) {
cout << "* ";
}
cout << endl;
}The break statement exits the innermost loop immediately, skipping the rest of the loop body and the condition check
Useful for early exit when a specific condition is met inside the loop
Example:
while (true) {
int num;
cin >> num;
if (num == 0)
break; // exit loop if input is zero
// process num
}File operations require the header
ofstream (output file stream) writes to files; ifstream (input file stream) reads from files
Files are opened via the constructor or the .open() method
Output files are created if they do not exist; input files must already exist
Reading from files often uses a loop to process data until end-of-file
Example:
#include Writing uses the insertion operator (<<); reading uses the extraction operator (>>)
Students often think prefix and postfix do the same thing. They produce the same final value in the variable, but they yield different values within the expression where they appear. In cout << x++, the old value is printed. In cout << ++x, the new value is printed.
Students often put a semicolon immediately after a while condition: while (count < 5);. This creates an empty loop body, and the intended block below runs only once (after the loop). The compiler will not warn you.
Students often assume a do-while loop checks its condition before the first iteration. It does not. The body always runs at least once.
Students often confuse which loop runs the full cycle in a nested pair. The inner loop completes all its iterations for each single iteration of the outer loop, not the other way round.
⚠️ Trace-through questions on prefix vs postfix operators are common. Be able to track the value of a variable across multiple lines that mix both forms.
⚠️ Know which loop to use: while for zero-or-more iterations, do-while for one-or-more, for when the count is known.
⚠️ Sentinel-controlled loops frequently appear in exam problems involving user input. Remember the priming read (the first cin before the loop).
⚠️ Nested loop output questions ("What does this code print?") are a staple. Count total iterations by multiplying outer x inner.
⚠️ The break statement only exits the innermost loop. In a nested loop, a break in the inner loop does not terminate the outer loop.
True or False: A while loop always executes its body at least once.
Fill in the blank: In the expression cout << x++;, the ______ value of x is printed.
True or False: A for loop can only count upwards.
Fill in the blank: A special value used to signal the end of input is called a ______ value.
True or False: In nested loops, the outer loop completes all its iterations before the inner loop starts.
Answers: 1. False (that describes do-while). 2. Original / old. 3. False (you can decrement: i--). 4. Sentinel. 5. False (the inner loop completes fully for each outer iteration).
Q: What is the output of the following code?
int x = 5;
cout << ++x << " ";
cout << x++ << " ";
cout << x;A: 6 6 7. The prefix ++x changes x to 6 and prints 6. The postfix x++ prints the current value 6, then increments x to 7. The final cout prints 7.
Q: What is the key difference between a while loop and a do-while loop?
A: A while loop tests the condition before each iteration, so the body may never execute. A do-while loop executes the body first, then tests the condition, so the body always runs at least once.
Q: Write a for loop that prints the even numbers from 2 to 20.
A: for (int i = 2; i <= 20; i += 2) { cout << i << " "; }
Q: How many times does the inner statement execute in the following nested loop?
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++) {
cout << "*";
}
}A: 12 times. The outer loop runs 3 times, and for each outer iteration the inner loop runs 4 times: 3 x 4 = 12.
Q: Why is a priming read necessary with sentinel-controlled loops?
A: The priming read gets the first input value before the loop begins. Without it, the loop condition would test an uninitialised variable on the first check, which is undefined behaviour.
Loops are the backbone of most function implementations. Once you learn functions and modular programming, you will write loops inside reusable functions rather than in main(). This connects to the functions material because loop-driven tasks (summing, searching, validating) are prime candidates for extraction into their own functions.
Nested loops become especially important when you reach arrays and two-dimensional arrays. Iterating over a 2D array is a direct application of nested for loops.
File I/O with loops connects to data processing more broadly. Reading records from a file until end-of-file is a sentinel-style loop pattern you will use throughout the course.
C++ loops, while loop C++, do-while loop, for loop syntax, pre-test loop, post-test loop, definite iteration, indefinite iteration, loop control variable, counter variable, accumulator pattern, sentinel-controlled loop, priming read, nested loops, break statement, infinite loop, loop body, iteration, repetition structure, fstream, ofstream, ifstream, file input output C++, increment operator, decrement operator, prefix increment, postfix increment, unary operator, lvalue