do...wile loop is similar to while loop, however is a difference between them: In while loop, condition is evaluated first and the statements inside loop body gets executed, on the other hand in do...while loop, statements inside do...while gets executed first and then condition is evaluated.
A simple example of while loop:
#include <stdio.h>
#include <conio.h>
void main()
{
int i = 1;
while(i < 5){
printf("protec");
i++;
}
getch();
}
Same example using do...while loop:
#include <stdio.h>
#include <conio.h>
void main()
{
int i = 1;
do{
printf("protec");
i++;
}while(i < 5);
getch();
}
Output:
Protec
Protec
Protec
Protec
Protec
Conclusion:
If you try and compare both the set of codes above, you will notice that there is not much difference between while and do while loop.
The major difference is that the while loop has the condition at the starting point whereas the do...while loop has the condition at the end of the loop.
Also, if you notice a minor fact here, there is a semicolon at the end of the do...while looping condition whereas it does not exists in case of the while loop.
The statements within the while loop will never execute if the while condition is false however in case of a do...while loop the block statements are going to be executed at least once.
while loop:
- Entry conditioned loop
- Condition is checked before loop execution
- Never execute loop if condition is false
- There is no semicolon at the end of while statement
- Lower execution time and speed
- No fixed number of iterations
do...while loop:
- Exit conditioned loop
- Condition is checked at the end of loop
- executes false condition at least once since condition is checked later
- There is semicolon at the end of while statement
- Higher execution time and speed
- Minimum one number of iterations
0 Comments:
Post a Comment
Please don't enter any spam link in the comment box.