Hi,
What is difference between while statement & do statement?
Hi,
What is difference between while statement & do statement?
Do while .. first does some code and then checks for a condition.
do-while is a exit controlled loop.
and
While first validates the condition before processing any code in the loop.
while is an entry controlled loop.
This is the major difference between the two!
A while statement (pre test) checks at the beginning of a loop to see whether the next loop iteration should occur. A do while statement (post test) checks at the end of a loop to see whether the next iteration of a loop should occur. The do statement will always execute the loop body at least once.
A "do while....." statement is a looping instruction to a program to repeat a stage in the program while some condition is true - e.g while a variable is negative, or, while one variable is less than another.
A "do for ....." statement is a looping instruction to a program to repeat a stage in the program a set number of times - e.g for steps = 1 to 10, or, for steps = 1 to (some variable).
Well, there is basically only one difference.
In do..while
int count = 0;
do
{
cout<<"Hello World";
}
while(count = -5);
the body is executed first and only then does the compiler come across the while( ) statement and the condition is checked. If true, it goes back to the do line and executes the body of the loop until the condition becomes false.
The output of the the above construct would be
Hello World
In the while statement, the condition is checked first, and only if it returns a true value is the body executed
int count = 0;
while(count = -5);
{
cout<<"Hello World";
}
There is no output for the above construct.
Hope the difference is clear.
If you need more assistance, I suggest you read Balaguruswamy's 'Let us C'
Source(s):
"Let us C"
by Balaguruswamy
Bookmarks