CodesJava

Easy learning with example program codes

CPP For Loop

CPP For Loop is a loop statement which can be used in various forms to execute a block of code continuously as long as the condition of the loop is true, and stops only when the condition fails. These are:

For Loop :

For loop is used to execute a group of action only for a specified number of times.

 

Syntax:

for(initialization; condition; increment/decrement)

{

code to be executed till the condition is true;

}

Nested For Loop :

Nested For loop is For loop inside a For loop and so on which is used to run multiple loop conditions.

 

Syntax:

for(initialization; condition; increment/decrement)

{

for(initialization; condition; increment/decrement)

{

code to be executed till the condition is true;

}

}

 

Example 1: Example of For loop

#include <iostream.h>
using namespace std;
int main()
{
int i;
for (i = 0; i <= 10; i++)
{
cout << i << endl;
}
return 0;
}

Output

0
1
2
3
4
5
6
7
8
9
10

Example 2: Example of Nested For loop

#include <iostream.h>
using namespace std;
int main()
{
int i,j;
for (i = 1; i <= 10; i++)
{
cout << i << endl;
for (j = 1; j <= i; j++)
{
cout << j;
}
cout << endl;
}
return 0;
}

Output

1
1
2
12
3
123
4
1234
5
12345
6
123456
7
1234567
8
12345678
9
123456789
10
12345678910

 

Please follow and like us:
error
Posted in CPP   








Copyright © 2019 CodesJava DMCA.com Protection Status