'for' statement in C
The for statement is used to execute a single statement or a block of statements repeatedly as long as the given condition is TRUE. The for statement has the following syntax and execution flow diagram...
At first, the for statement executes initialization followed by condition evaluation. If the condition is evaluated to TRUE, the single statement or block of statements of for statement are executed. Once the execution gets completed, the modification statement is executed and again the condition is evaluated. If it is TRUE, again the same statements are executed. The same process is repeated until the condition is evaluated to FALSE. Whenever the condition is evaluated to FALSE, the execution control moves out of the for block.
Example Program | Program to display even numbers upto 10.
#include<stdio.h>
#include<conio.h>
void main(){
int n ;
clrscr() ;
printf("Even numbers upto 10\n");
for( n = 0 ; n <= 10 ; n++ )
{
if( n%2 == 0)
printf("%d\t", n) ;
}
getch() ;
}
Output:
MOST IMPORTANT POINTS TO BE REMEMBERED
When we use for statement, we must follow the following...
- for is a keyword so it must be used only in lower case letters.
- Every for statement must be provided with initialization, condition, and modification (They can be empty but must be separated with ";")
Ex: for ( ; ; ) or for ( ; condition ; modification ) or for ( ; condition ; ) - In for statement, the condition may be a direct integer value, a variable or a condition.
- The for statement can be an empty statement.