Looping statement saves us from writing same code blocks again and again and executes the specific code block multiple times until some conditions are met. We may have known how many times we need to execute the code block or this decision could be made on the go. Looping has a solution for both cases.
'for' Loop in C
Most commonly used loop statement in C programming language is
'for'
loop. Syntax of'for'
loop is as given below.
- for(initialize expression; test condition; index modification expression)
- {
- Statement block
- }
The
'for'
loop generally includes three expressions separated by semicolon (;),- Init expression, which is executed first. You can initialize the loop control variable at this point. This expression is optional.
- Test condition is evaluated next. The body of loop is executed only if this condition evaluates to true. If this condition evaluates to false, the control moves to the next line after
'for'
loop - Index modification expression is executed after body of the loop. You can update the loop control variable at this location. After the execution of index modification expression, loop test condition is evaluated again and this procedure follows until the test condition is evaluated to false
'for' Loop Example in C
Suppose we want to print first 10 integers starting from 0. How we can write this using for loop? What will be the three expressions? Let’s look at the following program.
- #include<stdio.h>
- void main()
- {
- int index;
- for(index = 0; index < 10; index++)
- {
- printf("%d\n", index);
- }
- }
- Output:
- 0
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
First, the initialize expression assigns the value 0 to
'index'
variable. It declares that the loop will run with initial value 0. The second expression or test condition checks whether the value of the 'index'
is less than 10 or not. The last expression modifies the 'index'
variable, i.e. increments its value by 1. So, at start index is 0, the test condition is satisfied and the code block enclosed in braces is executed.