The for loop in C++

A for loop is a repetition control structure that allows you to efficiently write a loop that executes a specific number of times.
Syntax:

for(init;condition;increment )
{
  statement(s);
}

The init step is executed first, and does not repeat.
Next, the condition is evaluated, and the body of the loop is executed if the condition is true.
In the next step, the increment statement updates the loop control variable.
Then, the loop's body repeats itself, only stopping when the condition becomes false.
For example:

for(int x = 1;x<10;x++)
{
 // some code
}

Example:

The example below uses a for loop to print numbers from 0 to 9.

for(int a=0;a<10;a++)
{
  cout<<a<<endl;
}

Output:

0
1
2
3
4
5
6
7
8
9

It's possible to change the increment statement.

for(int a=0;a<50;a+=10)
{
  cout<<a<<endl;
}

Output:

0
10
20
30
40

You can also use decrement in the statement.

for(int a=10;a>=0;a-=3)
{
  cout<<a<<endl;
}

Output:

10
7
4
1

**Note:-**When using the for loop, don't forget the semicolon after the init and condition statements.


You've successfully subscribed to Developer Insider
Great! Next, complete checkout for full access to Developer Insider
Welcome back! You've successfully signed in
Success! Your account is fully activated, you now have access to all content.