The for loop statement is usually used to execute a single line of statement or block of statement for a specified number of times.
The syntax is:-
for ( initialization; condition; increment/decrement ) {
statement 1; } Inside for() loop, the first expression is used to initialize the variable , second expression is used to check condition true or false, and third statement is used to increment/decrement the variable. |
Remeber in while loop, we do initializtion, condition check and increment at three different places, here all three things has come at one place. Lets see one example.
Write a program to print 0 to 10 numbers on display.
#include<stdio.h> int main() { int count;for (count = 0; count <= 10; count++) { printf(“%d \t”,count);
} } Now we will see how compiler execute above C program :- |
Now write a program to print 5 to 10 numbers on display. think what to do, Just initialize variable equal to 5 in first expression of for() loop, see below.
#include<stdio.h> int main() {
int count;for (count = 5; count <= 10; count++) printf(“%d \t”,count);
} } The output is :- |