Table of Contents
In this lesson, you will learn about the ‘for’ loop in C++, its usage, including examples to understand the topic.
‘for’ loop in C++ Explained
The 'for'
loop is another type of loops in C++. It’s ideal to use if you know how many times the loop should iterate. For example, use the ‘for’ loop if you want to loop through an array of defined size.
Syntax of ‘for’ loop in C++
for (init; condition; increment) { // loop body }
Init: this step gets executed first. It contains the declaration and initialization of the loop iterator.
int i = 0;
Condition: is what the compiler evaluates each time the loop iterates. If the condition is met, the cursor goes inside the loop body and executes it.
i <= 5;
Increment: is the statement where the compiler increments the iterator, i, by a specific number. This action happens after the loop body is executed.
i++
The elements above, along with the loop body, form the 'for'
loop below
for (int i = 0; i <= 5; i++) { // Loop Body }
Flowchart
Example of ‘for’ loop in C++
#include <iostream> using namespace std; int main() { for (int i = 0; i <= 5; i++) { cout << i << endl; } return 0; }
Output
0
1
2
3
4
5
Backward or decrement ‘for’ loop in C++
So far, we have explained how for
loop works in an incremental way. But, what if you want the loop to go backward? The concept is easy; set the iterator to start from the number you want to start decrementing from, then compare the value of the iterator with the number you want to reach, and then decrement the iterator.
for (int i=5; i>0; i--)
Example of decrement ‘for’ loop in C++
#include <iostream> using namespace std; int main() { for (int i = 5; i > 0; i--) { cout << i << endl; } return 0; }
Output
5
4
3
2
1
Points to remember
- ‘for’ loop elements are: init, condition, increment, and the loop body.
- The loop iterator should be of int Data Type.
- ‘for’ loops can be incremental and decremental.