The difference between while and do while C++? [duplicate]

守給你的承諾、 提交于 2019-12-04 17:10:49

The while loop is an entry control loop, i.e. it first checks the condition in the while(condition){ ...body... } and then executes the body of the loop and keep looping and repeating the procedure until the condition is false.

The do while loop is an exit control loop, i.e. it checks the condition in the do{...body...}while(condition) after the body of the loop has been executed (the body in the do while loop will always be executed at least once) and then loops through the body again until the condition is found to be false.

Hope this helps :)

For Example: In case of while loop nothing gets printed in this situation as 1 is not less than 1, condition fails and loop exits

int n=1;
while(n<1)
    cout << "This does not get printed" << endl;

Whereas in case of do while the statement gets printed as it doesn't know anything about the condition right now until it executes the body atleast once and then it stop because condition fails.

int n=1;
do
   cout << "This one gets printed" << endl;
while(n<1);

The while loop first evaluates number < 10 and then executes the body, until number < 10 is false.

The do-while loop, executes the body, and then evaluates number < 10, until number < 10 is false.

For example, this prints nothing:

int i = 11;

while( i < 10 )
{
    std::cout << i << std::endl;
    i++;
}

But this prints 11:

int j = 11;

do
{
    std::cout << j << std::endl;
    j++;
}
while( j < 10 );

If you consider using a different starting value you can more clearly see the difference:

int number = 10;

while (number<10)
{
    cout << number << endl;
    number++
}
// no output

In the first example the condition immeditately fails, so the loop won't execute. However, because the condition isn't tested until after the loop code in the 2nd example, you'll get a single iteration.

int number = 10;

do
{
    cout << number << endl;
    number++
}
while (number<10);
// output: 10

The while loop will only execute of the conditions are met. Whereas the do while loop will execute the first time without verifying the conditions, not until after initial execution.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!