Home >>C Tutorial >C for loop
The for loop in the C language is basically used to iterate the statements or the part of a program repeated times. The for loop is most frequently used to traverse the data structures in C such as the array and linked list.
Here is the syntax of the for loop in C language:
for(Expression 1; Expression 2; Expression 3){ //code that is to be executed }
Let's understand the concept of for loop with these examples 1. Here is an example depicting the printing the table of 1:
#include<stdio.h> int main() { int i=0; for(i=1;i<=10;i++){ printf("%d \n",i); } return 0; }
2. Here is another example depicting the printing of the table of any number entered by the end user:
#include<stdio.h> int main() { int i=1,number=0; printf("Enter a number of your choice: "); scanf("%d",&number); for(i=1;i<=10;i++) { printf("%d \n",(number*i)); } return 0; }
Enter a number of your choice: 4
4 8 12 16 20 24 28 32 36 40Here is an example of the expression 1:
#include <stdio.h> int main() { int a,b,c; for(a=0,b=12,c=23;a<2;a++) { printf("%d ",a+b+c); } }
Here is another example of the Expression 1 for a better understanding of the topic:
#include <stdio.h> int main() { int i=1; for(;i<5;i++) { printf("%d ",i); } }
Here is an example of Expression 2:
#include <stdio.h> int main() { int i; for(i=0;i<=4;i++) { printf("%d ",i); } }
Here is another example of Expression 2:
#include <stdio.h> int main() { int i,j,k; for(i=0,j=0,k=0;i<4,k<8,j<10;i++) { printf("%d %d %d\n",i,j,k); j+=2; k+=3; } }
#include <stdio.h> int main() { int i; for(i=0;;i++) { printf("%d",i); } }
Here is an example of Expression 3:
#include<stdio.h> void main () { int i=0,j=2; for(i = 0;i<5;i++,j=j+2) { printf("%d %d\n",i,j); } }
The braces {} are used in order to define the scope of the loop {} braces are used. There is no need to use braces if the loop constitutes of only one statement. A loop can be possible without a body. The braces basically act as a block separator, i.e., the value of the declared variable inside for loop is only valid for that particular block.
Here is an example for the better understanding of the loop body:
#include<stdio.h> void main () { int i; for(i=0;i<10;i++) { int i = 20; printf("%d ",i); } }
There is no need to supply any expression in the syntax to produce an infinite for loop in the C language. As an alternative, the user need to provide two semicolons in order to validate the syntax of the for loop in C language. Then the result will act as an infinite for loop.
#include<stdio.h> void main () { for(;;) { printf("welcome to Phptpoint"); } }