A for loop in C++ repeatedly executes a block of code while a condition remains true. It is commonly used when the initialization, stopping condition, and update can be expressed together, such as counting from 1 to 10, traversing an array, or processing the elements of a container. This tutorial explains C++ for loop syntax, execution order, flowchart, examples, break, continue, infinite loops, nested loops, and range-based for loops.
C++ For Loop and When to Use It
A C++ for loop executes a statement or block of statements repeatedly based on a condition. It is especially useful when the loop has a clear initialization step, a condition that controls repetition, and an update performed after each iteration.
For example, to print the numbers from 1 through 5, a for loop can initialize a counter to 1, continue while the counter is at most 5, and increment the counter after every iteration.
C++ For Loop Syntax
Following is the syntax of for loop in C++.
for (initialization; condition; update) {
// statement(s)
}
The three expressions inside the parentheses have different roles:
- initialization runs once before the first condition check. It is often used to declare and initialize a loop counter, such as
int i = 0. - condition is checked before each iteration. The loop body executes only when this expression evaluates to
true. - update runs after the loop body on each completed iteration. It commonly increments or decrements the loop counter.
Execution Order of a C++ For Loop
When a for loop starts, the initialization expression is executed once. C++ then evaluates the condition. If the condition is true, the statements in the loop body execute. After the body finishes, the update expression runs, and the condition is checked again.
This condition-body-update cycle repeats until the condition evaluates to false. At that point, execution continues with the statement following the for loop.
C++ For Loop Algorithm
The execution of a standard C++ for loop can be described with the following steps.
- Start.
- Execute the initialization expression once.
- Evaluate the loop condition.
- If the condition is false, exit the loop.
- If the condition is true, execute the statements in the loop body.
- Execute the update expression.
- Return to the condition check and repeat.
The condition and update should normally allow the loop to reach its stopping condition. Otherwise, the loop may continue indefinitely.
C++ For Loop Flowchart
The following flowchart shows how initialization, condition checking, loop-body execution, and updating are connected in a C++ for loop.
C++ For Loop Examples
1. C++ For Loop to Print Numbers from 1 to 5
In this example, we shall write a for loop that prints numbers from 1 to 5. The variable i starts at 1, the loop continues while i <= 5, and i++ increases the value by one after each iteration.
main.cpp
#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 5; i++) {
cout << i << "\
";
}
}
Output
1
2
3
4
5
The initialization int i = 1 is performed only once. After every printed number, i++ increments the counter. When i becomes 6, the condition i <= 5 becomes false and the loop stops.
2. C++ For Loop to Compute Factorial
In this example, a for loop computes the factorial of 5. The variable factorial begins at 1 and is multiplied by every integer from 1 through n.
main.cpp
#include <iostream>
using namespace std;
int main() {
int n=5;
int factorial = 1;
for (int i = 1; i <= n; i++) {
factorial *= i;
}
cout << factorial << "\
";
}
Output
120
The loop performs the multiplication 1 × 2 × 3 × 4 × 5, producing 120.
3. C++ For Loop to Find the Sum of First N Natural Numbers
In this example, we shall use for loop to compute the sum of first N natural numbers. We shall write a for loop with condition that it is true until it reaches given number, and during each iteration, we shall add this number to the sum.
main.cpp
#include <iostream>
using namespace std;
int main() {
int n=5;
int sum = 0;
for (int i = 1; i <= n; i++) {
sum += i;
}
cout << sum << "\
";
}
Output
15
For n = 5, the loop adds 1 + 2 + 3 + 4 + 5, so the resulting sum is 15.
4. C++ For Loop That Counts Backward
A for loop does not have to increment its counter. The update expression can decrement it to iterate in descending order.
#include <iostream>
using namespace std;
int main() {
for (int i = 5; i >= 1; i--) {
cout << i << "\n";
}
return 0;
}
Output
5
4
3
2
1
Here, i-- decreases i after each iteration. The loop stops after i becomes 0 because the condition i >= 1 is then false.
C++ For Loop with break Statement
The break statement immediately terminates the nearest enclosing loop. Program execution then continues with the first statement after that loop.
In the following example, the for loop could count from 1 to 10, but the break statement terminates it when i becomes 4. Therefore, only 1, 2, and 3 are printed.
main.cpp
#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 10; i++) {
if (i == 4) {
break;
}
cout << i << "\
";
}
}
Output
1
2
3
C++ For Loop with continue Statement
The continue statement skips the remaining statements in the current iteration. In a for loop, control proceeds to the update expression and then the condition is tested for the next iteration.
In the following example, the loop processes values from 1 through 7. When i equals 4, continue skips the cout statement, so 4 does not appear in the output.
main.cpp
#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 7; i++) {
if (i == 4) {
continue;
}
cout << i << "\
";
}
}
Output
1
2
3
5
6
7
C++ For Loop for Arrays
An index-based for loop is commonly used to access array elements. The loop counter acts as the array index, usually starting at 0.
#include <iostream>
using namespace std;
int main() {
int numbers[] = {10, 20, 30, 40};
for (int i = 0; i < 4; i++) {
cout << numbers[i] << "\n";
}
return 0;
}
Output
10
20
30
40
The valid indexes of this four-element array are 0 through 3, which is why the condition uses i < 4.
Range-Based For Loop in C++
C++ also provides a range-based for loop for iterating directly over the elements of a range such as an array or std::vector. It is useful when the element itself is needed and an explicit numeric index is unnecessary.
C++ Range-Based For Loop Syntax
for (declaration : range) {
// statement(s)
}
C++ Range-Based For Loop with a Vector
The following program visits each element of a vector without manually maintaining an index.
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> numbers = {10, 20, 30, 40};
for (int number : numbers) {
cout << number << "\n";
}
return 0;
}
Output
10
20
30
40
On each iteration, number receives the value of the next element in numbers.
When the elements are large objects and the loop only needs to read them, a reference can avoid copying each element. For example, for (const auto& item : container) iterates using a read-only reference.
Infinite For Loop in C++
If the condition in a for loop always evaluates to true, the loop does not terminate on its own. This is called an infinite for loop.
For example, a condition such as true keeps the following loop running until the program is interrupted or the loop is terminated by another mechanism such as break.
main.cpp
#include <iostream>
using namespace std;
int main() {
for (int i = 1; true; i++) {
cout << i << "\
";
}
}
Output
The natural numbers are printed to the terminal indefinitely, until you interrupt and stop the program execution.
C++ also permits all three expressions of a traditional for loop to be omitted. Therefore, for (;;) is another common form of an intentional infinite loop.
for (;;) {
// repeat indefinitely
}
Nested For Loop in C++
A for loop can appear inside another for loop. This structure is known as a nested for loop. For every iteration of the outer loop, the inner loop can execute multiple iterations.
In the following example program, we shall print a pattern that resembles a triangle, using nested for loop.
main.cpp
#include <iostream>
using namespace std;
int main() {
for (int i = 1; i<=5; i++) {
for (int j = 1; j<=i; j++) {
cout << " *";
}
cout << "\
";
}
}
Output
*
* *
* * *
* * * *
* * * * *
The outer loop controls the rows. For each value of i, the inner loop runs from 1 through i and prints that many asterisks.
C++ For Loop Compared with While Loop
Both for and while loops repeat code while a condition is true. A for loop is often convenient when initialization, condition, and update belong together. A while loop can be clearer when repetition depends primarily on a condition and the number of iterations is not naturally represented by a counter.
For example, the following two loop structures follow the same basic sequence.
for (int i = 1; i <= 5; i++) {
// statements
}
int i = 1;
while (i <= 5) {
// statements
i++;
}
Common C++ For Loop Mistakes
Several small mistakes can change how many times a for loop executes or prevent it from terminating.
- Off-by-one conditions:
i < 5andi <= 5do not produce the same number of iterations. - Updating in the wrong direction: if a condition requires
ito decrease but the update usesi++, the loop may never reach its stopping condition. - Adding a semicolon after the for header:
for (...);creates an empty loop body, so the following block is not controlled by that loop. - Using an invalid array index: when traversing an array, the condition must prevent the counter from going beyond the array’s valid index range.
- Changing the loop counter unexpectedly inside the body: modifying the counter in multiple places can make the loop difficult to reason about.
C++ For Loop Summary
A traditional C++ for loop combines initialization, a continuation condition, and an update expression in one statement. Initialization runs once, the condition is checked before each iteration, and the update runs after the loop body. C++ also supports range-based for loops for directly traversing arrays and containers such as vectors.
In this C++ Tutorial, we learned the syntax and execution order of a for loop in C++, then used it for counting, factorial calculation, summation, array traversal, vectors, break, continue, infinite loops, and nested loops.
TutorialKart.com