Different Ways of Using For Loop in C Programming
In order to do certain actions multiple times , we use loop control statements.
For loop can be implemented in different verities of using for loop -
- Single Statement inside For Loop
- Multiple Statements inside For Loop
- No Statement inside For Loop
- Semicolon at the end of For Loop
- Multiple Initialization Statement inside For
- Missing Initialization in For Loop
- Missing Increment/Decrement Statement
- Infinite For Loop
- Condition with no Conditional Operator.
Way 1 : Single Statement inside For Loop
for(i=0;i<5;i++) printf("Hello");
- Above code snippet will print Hello word 5 times.
- We have single statement inside for loop body.
- No need to wrap printf inside opening and closing curly block.
- Curly Block is Optional.
Way 2 : Multiple Statements inside For Loop
for(i=0;i<5;i++) { printf("Statement 1"); printf("Statement 2"); printf("Statement 3"); if(condition) { -------- -------- } }
If we have block of code that is to be executed multiple times then we can use curly braces to wrap multiple statement in for loop.
Way 3 : No Statement inside For Loop
for(i=0;i<5;i++) { }
this is bodyless for loop. It is used to increment value of “i”.This verity of for loop is not used generally.
Way 4 : Semicolon at the end of For Loop
for(i=0;i<5;i++);
- Generally beginners thought that , we will get compile error if we write semicolon at the end of for loop.
- This is perfectly legal statement in C Programming.
- This statement is similar to bodyless for loop. (Way 3)
Way 5 : Multiple Initialization Statement inside For
for(i=0,j=0;i<5;i++) { statement1; statement2; statement3; }
Way 6 : Missing Increment/Decrement Statement
for(i=0;i<5;) { statement1; statement2; statement3; i++; }
however we have to explicitly alter the value i in the loop body.
Way 7 : Missing Initialization in For Loop
i = 0; for(;i<5;i++) { statement1; statement2; statement3; }
we have to set value of ‘i’ before entering in the loop otherwise it will take garbage value of ‘i’.
Way 8 : Infinite For Loop
i = 0; for(;;) { statement1; statement2; statement3; if(breaking condition) break; i++; }
Infinite for loop must have breaking condition in order to break for loop. otherwise it will cause overflow of stack.
Summary of Different Ways of Implementing For Loop
Form | Comment |
for ( i=0 ; i < 10 ; i++ ) Statement1; |
Single Statement |
for ( i=0 ;i <10; i++)
{
Statement1;
Statement2;
Statement3;
} |
Multiple Statements within for |
for ( i=0 ; i < 10;i++) ; | For Loop with no Body ( Carefully Look at the Semicolon ) |
for (i=0,j=0;i<100;i++,j++) Statement1; |
Multiple initialization & Multiple Update Statements Separated by Comma |
for ( ; i<10 ; i++) | Initialization not used |
for ( ; i<10 ; ) | Initialization & Update not used |
for ( ; ; ) | Infinite Loop,Never Terminates |