In this lesson, we will introduce loop statements, particularly the C++ ‘for loop,’ with a few examples.
Loops are used in computer programming to run a block of code repeatedly. Let’s imagine, for illustration, that we wish to display a message 100 times. Then we can utilize a loop rather than writing the print statement 100 times. That was just a simple illustration; using loops effectively can make our program considerably more efficient.
C++ offers three different types of loops:
This lesson’s primary emphasis is C++ “for loop”. In future lessons, we will learn about the additional types of loops.
Basic syntax
for (initialization; condition; increment/decrement) {
// body
}
Here, in the above syntax of for loop
Example
//Program prints 3 integers
#include <iostream>
using namespace std;
int main() {
int number;
for (number = 3; number >= 1; number--) {
cout << number << " ";
}
return 0;
}
Output
3 2 1
That’s how the program performs
| Variant | Variable Update | number >= 1 | Action |
|---|---|---|---|
| 1st | number = 3 | True | 3 is printed. The number is decreased to 3. |
| 2nd | number = 2 | True | 2 is printed. The number is decreased to 2. |
| 3rd | number = 1 | True | One is printed. The number is decreased to 1. |
| 4th | number = 0 | False | Program terminated |
A new range-based for loop was added in C++11 to support working with collections like arrays and vectors. The basic syntax is below:
Basic Syntax
for (variable: collection) {
// body of the sloop
}
In this case, the ‘for loop’ executes for every collection item, and the value is then assigned to the variable.
Example
//Program prints 5 integers
#include <iostream>
using namespace std;
int main() {
int numberArray[] = {
100,
200,
300,
400,
500
};
for (int number: numberArray) {
cout << number << " ";
}
return 0;
}
Output
100 200 300 400 500
An int array named numberArray has been declared and initialized in the program above. Here, a range-based for loop is utilized to access every array element. Five numbers will be printed.
This concludes the C++ for loop lesson. The next lesson will learn about the “while loop” in C++.