for statement in C language | Nesting of for in C language | for loop in C Language

for statement in C language | Nesting of for in C language | for loop in C Language

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;
}

for is a predefined keyword of C Language .

Initialize It 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 represents set of instructions 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 using for statement in  C Language.
#include<stdio.h>
int main()
{
int k;
for(k=1;k<=4;k++)
  printf("\n%d",k);
return(0);
}
Output
1
2
3
4

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 4, so statement printf(“\n%d”,k) gets executed showing 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 printf(“\n%d”,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 Language

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

Program to demonstrate the use of nested for statement.
#include<stdio.h>
int main()
{
int out,in;
for(out=1;  out<=3;  out++) 
{
      for(in=1;  in<=3;  in++) 
      printf("\n%d,%d",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 of c, looping statements in c, nesting of for statement in c
Back to: C Programming Language
Spread the love