Preview
for statement 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: In this part, we assign some value to the control variable which controls number of times the loop should execute.
Example
i=1;
Condition: It is a relational or logical expression to verify whether the for statement should continue or not.
Example
i<=5;
Update: Increasing or decreasing the value of control variable comes under this part.
Example
i++
Statements are set of instructions which will repeatedly execute as long as condition evaluates to true.
Example:
for(k=1;k<=4;k++)
k=1 is the initialization.
k<=4 is the condition.
k++ is the updation.
Program |
#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 this case one for statement is enclosed within another for statement.
Program |
#include<stdio.h> int main() { in 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.
Best Books of Computer Science