for statement in C Programming



In while and do while statement we need to write logic to repeatedly execute a block of statement by initializing a counter and incrementing it after a particular steps. This sometime looks tedious and decreases the readability of the program. The readability of the program can be improved by using for statement. Using for statement we can merge all the three parts i.e. assignment, condition checking and increment/decrementing.

Syntax:
for(initialization; test condition; increment/decrement){
/*block of statement*/
}

Initialization: setting up a loop counter to initial value
test condition: Testing the loop counter to determine whether the loop needs to be executed or not.
increment/decrement: Increment or decrement the loop counter value

Explanation:
The for loop is executed as follows:
1) The initial counter value is initialized. This initialization is done only once for the entire for loop.
2) After the initialization, test condition is checked. Test condition can be any relational or logical expression. If the test condition is satisfied i.e. the condition evaluates to true then the block of statement inside the for loop is executed.
3) After the execution of the block of statement, increment/decrement of the counter is done. After performing this, the test condition is again evaluated. The step 2 and 3 are repeated till the test condition returns false.

The above example for while loop can re-written as follows:
#include<stdio.h>
#include<conio.h>
void main(){
int i;
clrscr();
for(i=1; i<=5;i++){ printf("%d This will be repeated 5 times\n", i); } printf("End of the program"); getch(); } Output:
1 This will be repeated 5 times
2 This will be repeated 5 times
3 This will be repeated 5 times
4 This will be repeated 5 times
5 This will be repeated 5 times
End of the program

In the above program, value 1 is assigned to i. The for loop would be executed till the value of i is less than or equal to 5.
Note: It is necessary to write the semicolon in for loop as shown in the below:
for(i=0; i<10; i++)

Consider,
for(i=0; i<10;){
printf(“Interment/decrement not used above”)
i=i+1;
}
In the above program, Increment is done within the body of for loop. Still semicolon is necessary after the test condition.

Consider,
i=0;
for(; i<10;i++){
printf(“Interment/decrement not used above”)
}
In the above program, Initialization is done before the start of for loop. Still semicolon is necessary before the test condition.
Note:
We can initialize multiple variables in initialization section but only one test condition is allowed.


Responses

0 Respones to "for statement in C Programming"

Post a Comment

 

Total Pageviews

Return to top of page Copyright © 2011 | Kuppam Engineering College Converted into Blogger Template by Mohan Murthy