Programs to understand for loops for iterative statements.
Loops : Loops executes a block of statements number of times until the condition becomes false.
For Loops : A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times.
Syntax :
for (initialization; condition ; increment / decrement) { //Statements to execute } |
---|
- Initialization : In this expression we have to initialize the loop counter to some value. for example: int i=1;
- Condition: In this expression we have to test the condition. If the condition evaluates to true then we will execute the body of loop and go to update expression otherwise we will exit from the for loop. For example: i <= 10;
- Increment / Decrement: After executing loop body this expression increments/decrements the loop variable by some value. for example: i++ or i--;
Example-1 :
#include<stdio.h> #include<conio.h> void main() { int i; for (i=1; i<=5; i++) { printf("%d\n", i); } } |
---|
Output :
1
2
3
4
5
Example-2 (Nested For Loop) :
#include<stdio.h> #include<conio.h> void main() { int i,j; for (i=0; i<2; i++) { for (j=0; j<4; j++) { printf("%d, %d\n",i,j); } } } |
---|
Output :
0, 0
0, 1
0, 2
0, 3
1, 0
1, 1
1, 2
1, 3
Example-3 (Infinite for loop) :
for(;;) { printf("welcome to GoEduHub Technologies"); } |
---|
Example-4 Multiple Initialisation inside for loop :
#include<stdio.h> #include<conio.h> void 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; } } |
---|
Output :
0 0 0
1 2 3
2 4 6
3 6 9
4 8 12
For more RTU/BTU II Sem Computer Programming Lab Experiments CLICK HERE