In this tutorial, you will learn about c programming for loop and how it is used in programs. Relevant examples will follow to highlight for loop concept in C.
for loop in C programming
While writing programs, we might need to repeat same code or task again and again.
For this C provides a feature of looping which allows a certain block of code to be executed repeatedly unless or until some sort of condition is satisfied even though the code appears once in a program.
There are three types of loops in C programming.
- for loop
- while loop
- do … while loop
Structure of for loop in C
for ( statement1; statement2; statement3) { //body of for loop }
Here, statement1
is the initialization of loop, statement2
is the continuation of the loop. Normally, it is a test condition and statement3
is increment or decrement of a control variable as per need.
Here is the block diagram to show how a for loop works:
Header format of for loop in C
How for loop works?
for ( counter = 1; counter <= 5; counter++) { printf("hello\n"); //body of for loop }
In the above example, counter
is the control variable and counter = 1
is the first statement which initializes counter
to 1.
The second expression, counter <= 5
is the loop continuation condition which repeats the loop till the value of counter
exceeds 5.
Finally, the third expression, counter++
increases the value of counter
by 1.
So the above piece of code will print 'hello'
five times.
Example of for loop
#include<stdio.h>
int main()
{
int n;
printf("How many time you want to print?"\n);
scanf(" %d ", &n);
for ( i = 1; i <= n; i++) //for loop which will repeat n times
{
printf("simple illustration of for loop"\n);
}
return 0;
}
Output
How many time you want to print?
2
simple illustration of for loop
simple illustration of for loop
Explanation:
Suppose the user entered value 2. Then the value of n
will be 2.
The program will now check test expression,'i <= n'
which is true and the program will print 'simple illustration of for loop'
.
Now the value of 'i'
is incremented by one i.e. i = 2
and again program will check test expression, which is true and program will print 'simple illustration of for loop'
.
Again the value of 'i'
is incremented by 1 i.e. i = 3
This time test expression will be false and the program will terminate.