for loop in C

for loop in C

  • For loop is a loop in which all three statements initialization, condition and increment/decrement is given in a single step (before the code). 
  • The for loop in C language is also used to iterate the statement or a part of the program several times
  • So code may be executed for 0 or more times.
  • It is good if number of iteration(repetition) is known by the user.
The syntax of for loop in c language is given below:

for(initialization;condition;incr/decr)
{  
//code to be executed  


Flowchart of For Loop
  • But, we can initialize and increment or decrement the variable also at the time of checking the condition in for loop.

When use for loop in C

  • For loop is better if number of iteration is known by the programmer.

Example of for loop in C language

  • Let's see the simple program of for loop that prints table of 1.
  1. #include <stdio.h>      
  2. #include <conio.h>      
  3. void main(){      
  4. int i=0;    
  5. clrscr();      
  6. for(i=1;i<=10;i++){    
  7. printf("%d \n",i);    
  8. }      
  9. getch();      
  10. }      

Output

1243586710

C Program : Print table for the given number using C for loop

  1. #include <stdio.h>    
  2. #include <conio.h>    
  3. void main(){    
  4. int i=1,number=0;  
  5. clrscr();    
  6.   
  7. printf("Enter a number: ");  
  8. scanf("%d",&number);  
  9.   
  10. for(i=1;i<=10;i++){    
  11. printf("%d \n",(number*i));  
  12. }  
  13. getch();    
  14. }    

Output

Enter a number: 

2

2

4

8
6
12
10
20
14
16
18


Enter a number: 
1000
1000
2000
4000
3000
9000
5000
6000
8000
7000
10000


Infinitive for loop in C

  • If you don't initialize any variable, check condition and increment or decrement variable in for loop, it is known as infinitive for loop.
  • In other words, if you place 2 semicolons in for loop, it is known as infinitive for loop.
  1. for(;;)
  2. {  
  3. printf("infinitive for loop example by https://mskuthar.blogspot.com/");  
  4. }  
If you run this program, you will see above statement infinite times.

Post a Comment

Previous Post Next Post