Monday, February 1, 2010

Comparison Among Different Loops - for, while and do while loop

I will discuss about the differences among different types of loop in this post.


Difference between while and do-while loop


while loop is a entry control loop where the loop control variable must be initialized first and after that the condition of the loop will be checked. If the condition is true, then only the loop body will be executed. Inside the loop bode the loop control variable will be re-initialized for re-checking the condition. So if the condition of the loop is set to false at the beginning, the loop will not execute for a single time. In while loop the control statement is placed before the body of the loop.

do while loop is an exit control loop where the loop body will be executed unconditionally for the first time and we can initialize the loop control variable inside the loop body.After executing the body the loop condition is checked. So in do-while loop the loop will execute for at least one time. In do while loop, body of the loop is placed before the control statement of the loop.

Difference between while and for loop

Both while and for loop are entry control loop, means condition is checked first and if the condition is true then the body executes. In for loop all the three statements-initialization, condition checking and reinitialization statements are placed in one position while in while loop, they are placed in different position. Although the sequence of execution is same for both the loops. For loop is best suited when the loop control variable is to be reinitialized with a fixed sequence of values and when the value with which the loop control variable is to be reinitialized depends upon the user, while loop is best.

1 comment:

Subscribe via email

Enter your email address:

Delivered by FeedBurner