C For Loop vs While Loop | while Loop & do-while Loop
In this tutorial, we will learn about Difference between For Loop & While Loop, and while Loop & do-while Loop.
For Loop vs While Loop
for loop | while loop |
---|---|
Initialization may be either in loop statement or outside the loop. | Initialization is always outside the loop. |
Once the statements is executed then after increment is done. | Increment can be done before or after the execution of the statement. |
It is normanlly used when the number of iteration is known. | It is normally used when the number of iterations is unknown. |
Condition is a relational expression. | Condition may be expression or non-zero value. |
It is used when initialization and increment is simple. | It is used for complex initialization. |
For is entry Controlled loop. | while is also entry controlled loop. |
for (initialization; condition; iteration) {statement(s);} | while(condition){statement(s);} |
for loop used only when we already knew the number of iterations. | while loop used only when the number of iteration are not exactly known. |
While Loop vs do-while Loop
while loop | do-while loop |
---|---|
Condition is checked first then statement(s) is executed | Statement(s) is executed atleast once, thereafter condition is checked. |
It might occur statement(s) is executed zero times, if condition is false. | Atleast once the statement(s) is executed. |
No semicolon at the end of while. while(condition) | Brackets are always rewuired. |
Variable in condition is initialized before the execution of loop. | Variable may be initialized before or within the loop. |
while loop is entry controlled loop. | do-while loop is exit controlled loop. |
while(condition){statement(s);} | do{statement(s)}while(condition); |
The iteration do not occur if, the condition at the first iteration, appears false. | The iteration occurs atleast once even if the condition is false at the first iteration. |
We hope that this tutorial helped you develop better understanding of the concept of Difference b/w for loop, while loop & do-while loop in C.
Keep Learning : )