Looping statement defines a set of repetitive statements . These statements are repeated, with same or different parameters for a number of times. For loop is an entry controlled looping statement. It is used to repeat set of statements until some condition is met. Looping statements whose condition is checked prior to the execution of its body is called as Entry controlled loop.
In real life we come across situations when we need to perform a set of task repeatedly till some condition is met. Such as – sending email to all employees, deleting all files, printing 1000 pages of a document. All of these tasks are performed in loop. To do such task C supports looping control statements.
For loops give the following functionality:
The syntax of the for loop is:
for (variable-initialization ; condition ; variable-update)
{
// statements inside the body of loop
}
Parts of for loop
Any repetition contain two important part - What to repeat and number of repetition? variable-initialization, condition and variable-update define number of repetition and body of loop define what to repeat.
Note:
All four parts of a for loop is optional. Hence you can write a for loop without initialization, condition, update or body. However, you must follow the syntax and specify semicolons.
How for loop works?
Flowchart of for loop
Example program to demonstrate for loop
/**
* C program to print natural numbers from 1 to 10.
*/
#include <stdio.h>
int main()
{
/* Declare loop counter variable */
int count;
/* Run a loop from 1 to 10 */
for(count=1; count<=10; count++)
{
/* Print current value of count */
printf("%d ", count);
}
return 0;
}
Output
1 2 3 4 5 6 7 8 9 10