Loops
Many real-world situations require performing the same task repeatedly. In this lesson, you will learn how C++ uses while, do...while, and for loops to automate repetitive tasks efficiently.
Introduction
In the previous lesson, you learned how to make decisions using conditional statements. However, many programming tasks require the same operation to be performed repeatedly.
For example, a program may need to display numbers from 1 to 100, print a multiplication table, process thousands of customer records, or repeatedly ask a user for input. Writing the same statements again and again would make the program unnecessarily long and difficult to maintain.
C++ provides loops to repeatedly execute code without manually writing the same statements multiple times.
What is a Loop?
A loop is a control structure that repeatedly executes a statement or block of statements according to a condition.
Instead of writing the same code many times, a programmer writes the code once and allows the loop to repeat it.
Start
↓
Check Condition
↓
Execute Code
↓
Update
↓
RepeatA loop repeats instructions until its repetition condition causes the loop to stop.
Why Do We Need Loops?
Without Loops
- The same code must be written repeatedly.
- Programs become unnecessarily lengthy.
- Repeated code is difficult to modify.
- Code duplication increases the chance of mistakes.
- Large repetitive tasks become impractical.
With Loops
- Reduce code duplication.
- Automate repetitive tasks.
- Save development time.
- Improve readability.
- Make repeated operations easier to maintain.
Real-World Analogy
Imagine a teacher asking a student to write "Practice Makes Perfect" 100 times. Writing 100 separate instructions would be unnecessary.
A loop works in the same way. It repeatedly performs an instruction while controlling how and when the repetition should end.
How a Loop Works
Most counter-controlled loops can be understood through four basic parts: initialization, condition checking, execution, and update.
1. Initialization
Creates or prepares the value used to control the loop.
2. Condition
Determines whether another iteration should begin.
3. Loop Body
Contains the statements performed during each iteration.
4. Update
Changes loop state so that progress can be made toward termination.
A loop must eventually reach a state where repetition stops unless an intentionally continuous loop is required.
Types of Loops in C++
C++ provides several loop structures. The three fundamental loops introduced in this lesson are while, do...while, and for.
while
Checks the condition before each iteration.
do...while
Executes the body before checking the condition.
for
Provides initialization, condition, and update in a compact loop structure.
1. The while Loop
The while loop repeatedly executes its body while its condition evaluates to true. Because the condition is checked before the body, a while loop may execute zero times.
while (condition)
{
// Statements
}#include <iostream>
int main()
{
int number = 1;
while (number <= 5)
{
std::cout << number << std::endl;
number++;
}
return 0;
}Explanation
- number is initialized with the value 1.
- The condition number <= 5 is checked before each iteration.
- The current value of number is displayed.
- number++ increases the value by 1.
- The loop repeats while number is less than or equal to 5.
- When number becomes 6, the condition is false and the loop ends.
1
2
3
4
5A while loop is useful when repetition depends primarily on a condition and the number of iterations is not naturally expressed as a fixed count.
2. The do...while Loop
The do...while loop checks its condition after executing the loop body. Therefore, the body executes at least once.
do
{
// Statements
}
while (condition);A do...while statement requires a semicolon after the closing while condition.
#include <iostream>
int main()
{
int number = 1;
do
{
std::cout << number << std::endl;
number++;
}
while (number <= 5);
return 0;
}Execution Process
- number starts with the value 1.
- The loop body executes immediately.
- The current number is displayed.
- number is increased.
- The condition is checked after the body.
- The loop repeats while the condition remains true.
while Loop
- Condition is checked first.
- The body may execute zero times.
- Useful when execution should happen only after validation.
do...while Loop
- The body executes first.
- The body always executes at least once.
- Useful when one initial execution is required before validation.
int number = 10;
while (number <= 5)
{
std::cout << "while";
}
// Executes zero times
do
{
std::cout << "do...while";
}
while (number <= 5);
// Executes once3. The for Loop
The for loop provides a compact structure for repetition. It is especially common for counter-controlled loops because initialization, condition, and update appear together.
for (initialization; condition; update)
{
// Statements
}Initialization
Runs once before the first condition check.
Condition
Checked before each iteration.
Update
Runs after each completed iteration.
#include <iostream>
int main()
{
for (int i = 1; i <= 5; i++)
{
std::cout << i << std::endl;
}
return 0;
}Execution Process
- int i = 1 runs once before the loop begins.
- i <= 5 is checked before each iteration.
- The current value of i is displayed.
- i++ executes after the loop body.
- The condition is checked again.
- When i becomes 6, the condition is false and the loop ends.
1
2
3
4
5A for loop is commonly preferred when initialization, continuation condition, and update naturally belong together, especially in counter-controlled repetition.
Comparison of Loops
| Loop | Condition Checked | Executes At Least Once? | Common Use |
|---|---|---|---|
| while | Before the body | No | Condition-controlled repetition |
| do...while | After the body | Yes | Tasks requiring one initial execution |
| for | Before the body | No | Counter-controlled repetition |
These loop types can sometimes solve the same problem. Choose the structure that expresses the repetition most clearly.
Memory Representation
Consider the loop for (int i = 1; i <= 3; i++). The loop variable changes during each iteration.
Start:
i → 1
Iteration 1:
Condition: 1 <= 3 → true
Body executes
Update: i becomes 2
Iteration 2:
Condition: 2 <= 3 → true
Body executes
Update: i becomes 3
Iteration 3:
Condition: 3 <= 3 → true
Body executes
Update: i becomes 4
Final Check:
Condition: 4 <= 3 → false
Loop endsWhen i is declared in the initialization section of the for loop, its scope is limited to the for statement and its body.
Real-World Applications
Banking
Process transaction collections, account records, and repeated calculations.
Student Management
Process students, marks, attendance records, and reports.
Games
Run repeated updates for movement, input processing, simulation, and rendering.
E-Commerce
Process product collections, orders, shopping cart items, and search results.
Scientific Computing
Perform repeated calculations, simulations, and numerical processing.
Data Processing
Process records, collections, files, and streams of input.
Common Beginner Mistakes
If the condition depends on a variable that never changes, the loop may never reach its stopping condition.
A condition that always remains true causes the loop to continue indefinitely unless another control statement exits it.
A condition that is false from the beginning may prevent an entry-controlled loop from executing.
A semicolon immediately after a while or for statement creates an empty loop body.
Using < instead of <=, or starting from the wrong value, can cause one too few or one too many iterations.
Incrementing a variable when the condition requires it to decrease can prevent the loop from terminating.
int number = 1;
while (number <= 5)
{
std::cout << number;
// Missing:
// number++;
}number remains 1, so number <= 5 remains true and the loop does not terminate normally.
while (true)
{
// Repeats until some operation
// inside the program exits the loop
}Some event loops, servers, and interactive programs intentionally repeat continuously. The problem is an infinite loop that occurs unintentionally or cannot be controlled correctly.
for (int i = 1; i >= 5; i++)
{
std::cout << i;
}
// 1 >= 5 is false,
// so the loop body never executes.while (number <= 5);
{
std::cout << number;
}The semicolon is the loop body. If number does not change while the empty loop runs, the program may become stuck before reaching the block below it.
// Prints 1 through 4
for (int i = 1; i < 5; i++)
{
std::cout << i << std::endl;
}
// Prints 1 through 5
for (int i = 1; i <= 5; i++)
{
std::cout << i << std::endl;
}Best Practices
- Choose the loop structure that makes the repetition easiest to understand.
- Ensure that a loop has a clear termination strategy.
- Update loop-control state correctly.
- Use for loops when initialization, condition, and update naturally belong together.
- Use while loops when repetition is primarily controlled by a condition.
- Use do...while when the body must execute before the first condition check.
- Use meaningful loop variable names when the variable represents a specific concept.
- Use simple names such as i for small conventional counting loops when the meaning is obvious.
- Watch carefully for off-by-one errors.
- Avoid deeply complicated loop conditions.
- Use braces consistently for clarity and safer maintenance.
- Do not create infinite loops unless continuous repetition is intentional and properly controlled.
Frequently Asked Questions
What is a loop?
A loop is a control structure that repeatedly executes statements according to a repetition condition.
What are the three basic loops introduced in C++?
while, do...while, and for.
Which loop always executes its body at least once?
The do...while loop, because its condition is checked after the body.
Can a while loop execute zero times?
Yes. If its condition is false before the first iteration, the body is skipped.
Can a for loop execute zero times?
Yes. If its condition is false at the first check, the body does not execute.
Which loop is commonly used for counting?
A for loop is commonly used for counter-controlled repetition because initialization, condition, and update are grouped together.
What is an infinite loop?
An infinite loop is a loop that continues indefinitely because no normal stopping condition is reached.
Are infinite loops always errors?
No. Some programs intentionally run continuous loops, but unintended infinite loops are bugs.
What is an off-by-one error?
It is a boundary mistake that causes a loop to execute one too many or one too few times.
What happens if I put a semicolon after while?
The semicolon becomes an empty loop body. This can cause unexpected behavior or an infinite loop.
Key Takeaways
- Loops automate repeated execution.
- A loop repeatedly executes statements according to its control logic.
- while checks its condition before the body.
- do...while checks its condition after the body.
- A do...while body executes at least once.
- for groups initialization, condition, and update together.
- Loop variables and conditions must progress toward termination.
- Incorrect updates can create infinite loops.
- Boundary mistakes can create off-by-one errors.
- Accidental semicolons can create empty loops.
- Different loop structures may solve the same problem.
- The clearest loop structure is usually the best choice.
Summary
Loops are fundamental control structures that automate repetitive work. Instead of writing the same instructions repeatedly, a program can use a loop to execute them according to a condition.
The while loop checks its condition before execution, the do...while loop checks its condition after execution, and the for loop provides a compact structure for initialization, condition checking, and updating. Understanding how loops begin, repeat, update, and terminate is essential for writing reliable programs.
Loops are used throughout real applications for processing records, displaying collections, performing calculations, running simulations, handling game updates, and many other repetitive tasks. Mastering loops provides an important foundation for working with functions, arrays, collections, and more advanced programming concepts.