May 1, 2011

for, while and do..while

for, while and do..while are the three types of loops available for almost all imperative languages. But the concept is same for all of them and they only carry slight variations is syntax.

One of the concerns when writing a loop is to identify which of the above three is most suitable. It is important if efficiency is an expectation of your program.

while
while(condition){
  //code here
}

do..while
do{
  //code here
}while(condition)

for
for( i = 0; i < 10; i++){
  //code here
}

while vs do..while
The while and do..while loops both loop until a condition is false. But the difference between them is that the while loop will check the condition before the first iteration and the do..while will perform the first iteration and then after check the condition. Therefore the change is in the first iteration and after it is finished, there is no difference between the two loops.

while vs for

A common mis-use of the while loop is using a counter within it. That is use a counter to keep track of the number of iterations of the loop and making sure to exit the loop when the counter is exceeded.

i = 0;
while ( i < 5){
  //code here
i++;
}

The purpose of the for loop is to be used in such situations.

for ( int i = 0; i < 5; i++){
  //code here
}

Therefore, the main difference between the two would be to use the for loop when the number of iterations is known and use the while or do..while when unknown. But there is no real difference in efficiency for a situation as above. Hence, I believe its more of de facto.

No comments:

Post a Comment