The C++ for
loop is used to run through a code block a specific number of times.
The syntax of for loop is given below.
for(initialization; condition; incr/decr){ //code to be executed }
The for
loop uses three parameters. The first one initializes a counter and is always executed once before the loop. The second parameter holds the condition for the loop and is checked before each iteration. The third parameter contains the increment/ decrement of the counter and is executed at the end of each loop.
#include <iostream> using namespace std; int main() { for(int i=1;i<=10;i++){ cout<<i <<"\n"; } }
A for
loop is powerful and flexible. We can initialize more than one variable, test a compound logical expression, and execute more than one statement. When the initialization and action sections contain more than one statement, they are separated by commas.
Here’s an example:
for (int x = 0, y = 0; x < 10; x++, y++) { std::cout << x * y << “\n”; }
This loop has an initialization section that sets up two integer variables: x and y separated by comma between the two declarations. The loop’s test section tests whether x < 10 and the loop’s action section increments both integer variables, using a comma between the statements. The body of the loop displays the product of multiplying the variables together.
Each section of a for
loop also can be empty. The semicolons are still there to separate sections, but some of them contain no code.
Here’s an example:
int x = 0; int y = 0; for ( ; x < 10; x++, y++) { std::cout << x * y << “\n”; }
We can use array in for
loop. C++11 introduced a range-based for
loop syntax for iterating through arrays and other container types. At each iteration the next element in the array is bound to the reference variable, and the loop continues until it has gone through the entire array.
int a[3] = {1, 2, 3}; for (int &i : a) { cout <<i; // "123" }
In C++, for
loops can be nested with one loop sitting in the body of another for loop, it is known as nested for loop. The inner loop will be executed in its entirety for every execution of the outer loop. So if outer loop and inner loop are executed 3 times, inner loop will be executed 3 times for each outer loop i.e. total 9 times.
Let's see a simple example of nested for loop in C++.
#include <iostream> using namespace std; int main () { for(int i=1;i<=3;i++){ for(int j=1;j<=3;j++){ cout<<i<<" "<<j<<"\n"; } } }
It is option of leaving out any one of the parameters of for
loop. If we don't add any parameters and use double semicolon in for loop, it will be executed infinite times.
Let's see a simple example of infinite for loop in C++.
#includeusing namespace std; int main () { for (; ;) { cout<<"Infinitive For Loop"; } }