for statement in C++| Nesting of for statement in C++ | for loop in C++

for statement in C++| Nesting of for statement in C++ | for loop in C++

for statement is a looping statement used to repeat a set of statements for a specified number of times. Syntax of for statement is:

for(Initialize;Condition;Update)
{
Statements-Block;
}

for is a keyword of C++.

Initialize is the way to store initial value in the control variable which controls how many times loop would execute.

Example

i=1;

Condition: It refers to any relational or logical expression used to check whether the loop should continue or not.

Example

i<=5;

Update: It is the way to increase or decrease the value of control variable.

Example

i++

Statements-Block  refers to set of C+++ statements which will repeatedly execute as long as condition is true.

Example:

for(k=1;k<=4;k++)

k=1 is the initialization.

k<=4 is the condition.

k++ is the updation.

 

Program of for statement in C++.
#include<iostream> 
using namespace std;
int main()
{
 int k;
 for(k=1;k<=4;k++)    
   cout<<endl<<k;
return 0;
}
Output
1
2
3
4
5

Description of above program

In the program, control variable k has been strored value 1. Value of k is then compared with 4. It is less than equal to  4, so statement cout<<endl<<i;  gets executed displaying value of k i.e. 1.

Then control goes to updation statement k++which increases the value of k by 1. k becomes 2.

Again k<=5 is tested. which is true so cout<<endl<<k; gets executed.

Again updation k++ is performed followed by condition k<=4. This process goes on as long as condition is true.

Nesting of for statement in C++

In this case one for statement is enclosed within another for statement.

Program to demonstrate the use of nested for statement.
#include<iostream> 
using namespace std;
int main()
{
int out,in;
for(out=1;  out<=3;  out++) 
{
      for(in=1;  in<=3;  in++) 
      cout<<endl<<out<<”,”<<in;
}
return(0);
}
Output
1,1
1,2
1,3
2,1
2,2
2,3
3,1
3,2
3,3

Description of above program

In the above program, for one value of outer loop, inner loop will execute completely

for out=1, in  will execute complete i.e. 1,2,3.

for out=2, in will again execute complete i.e. 1,2,3.

Similarly for out=3, in will work complete i.e. 1,2,3.

This process is repeated for next values of out i.e. 2 and 3.

Spread the love
Lesson tags: for loop in C, for statement in C++, nesting of for statement in c, Program of for statement in C++.
Back to: C++ Programming Notes
Spread the love