C programming language provides the for
loop in order to iterate over a given list. The for loop provides an initialization value with the condition to jump the next step and the incrementation value. The “for” loop can be used in different cases to process multiple data, search for something, etc. In this tutorial, we examine how to use the “for” loop for different cases.
for Loop Syntax
The for loop has the following syntax. When the for loop ends the execution continues with the after for loop statements.
for (INIT;CONDITION;INCREMENT){
STATEMENTS;
}
- INIT is the first step in the for loop. When the for loop is reached the INIT is executed one time and do not executed later again. INIT is used for initization oppurtunities like
loop control variable
creation and assignment. The INIT is optional and can empty by not putting any statement and using semicolon. - CONDITION is the for loop control condition where it is a boolean result. If the CONDITION evaluated as
True
the for loop continue execution and jumps to next step. If the CONDITION evaluated asFalse
the for loop execution is stopped. The CONDITION is required. - INCREMENT is executed after every step. Mainly it is used to change the state of the CONDITION. Generally integers are incremented in the INCREMENT part.
- STATEMENTS is single or more statements which are executed in every step.
for Loop Example
#include <stdio.h>
int main () {
int a;
/* for loop example*/
for( a = 1; a < 10; a = a + 1 ){
printf("Current value of a: %d\n", a);
}
/* for loop example with a++ incrementation*/
for( a = 1; a < 10; a++ ){
printf("Current value of a: %d\n", a);
}
return 0;
}
for Loop Array Example
The for loop can be used to iterate over an array. A char array can be iterated with the for loop. In the following example, we loop over the char array “name”.
#include <stdio.h>
int main () {
char a[10]="ismail"
/* Loop over char array*/
for( a = 0; a < 10; a++ ){
printf("Current character is : %c\n", name[a]);
}
return 0;
}