-1

Can someone explain the purpose of having two different types of while loops? I am new to programming. Also supply example situations with the proper while loop if possible.

I understand how to use a while loop. This is what I made:

bool myBool = true;
int i = 0;

while (myBool) {
  if (i > 10) {
      myBool = false;
  }
  i = i + 1;
}

6 Answers6

9

A while loop will only execute when the boolean condition is true.

    while (true) {
        // INSERT CODE HERE
        std::cout << "boolean condition is true - inside my while loop";
    }

A do while whill check the boolean condition after the loop executes once.

    do {
        // INSERT CODE HERE
        std::cout << "inside my while loop regardless of boolean condition";
    } while (true);

Explicitly: the do while loop is guaranteed to execute at least once, whereas the while loop is not guaranteed to execute at all.

Similarly,

while (false) {
    // INSERT CODE HERE
    std::cout << "this will never execute";
}

will never execute and

do {
    // INSERT CODE HERE
    std::cout << "this will execute only once";
} while (false);

will execute once.

bcr
  • 950
  • 8
  • 28
4

The do while loops are control flow statements, they execute a block of code at least once and then the iteration of loops depends on the condition which is checked at the bottom of the loop, They are best to use when you want at least once the loop to be executed, for ex

#include <stdio.h>

int main () {


   int c = 50;

   /* The do will be executed */
   do {
      printf("value of c: %d\n", c);
      c = c + 1;
   }while( c < 20 );//It will depend on the condition
 printf("any string");
   return 0;
}

Here is a Flow diagram of do while loop enter image description here

Dheeraj Joshi
  • 1,522
  • 14
  • 23
2

Simple answer is while loop will execute only if condition inside of while statement is true. do while loop will execute once regardless of the while statement condition.

#include <iostream>
using namespace std;

int main(int argc, char *argv[]){
    int i = 1;
    while( i < 1){     // this loop will never execute as 1 is not smaller then 1
       i++;            // if the loop was working we would get print 2 here  
       cout << i << endl;
    }

    cout << i << endl; // this one will print outside of loop value 1

    do{
       i++;            // increase i to 2
       cout << i << endl;  // this will print 2
    } while (i < 1);   // This loop will execute at least once and as the condition of 2 is not smaller then 1 it will exit after one execution 
return 0;
}
MarkoShiva
  • 83
  • 1
  • 2
  • 10
2

The difference between while and do-while is that in

while (<condition>)
{
  //statements
}

we can control whether to enter the loop by using the test condition. Whereas in

do
{
 //statements
} while (<condition>);

the code has to enter the loop at least once before it can exit by using the condition. So if we want to enter the loop at least once we should use do-while whereas if we want to test and decide whether to enter the loop or not, we have to use while.

AG_BOSS
  • 114
  • 10
1

To explicitly answer your first question:

  1. Why does C++ have different kinds of loops? -> Legacy. Other languages (in particular, C) before C++ had this feature, so C++ chose to have it.

  2. Why did other languages have it? -> This gets muddy, but a good explanation is that early languages often did not have optimizing compilers, so your code mapped quite directly to machine code. Providing various loop syntaxes allowed programmers to write structured code that still generates good machine code for their particular case.


In practice, it is rare to see a true do {} while () loop. This may be because for (or range-based for) and while () {} have strictly greater capabilities than do {} while (): An unconditional first loop iteration is possible with every loop, but the reverse is not true. In the very common case of iterating over a (possibly empty) sequence, having a guaranteed loop body execution like do {} while () is actually wrong.

There are plenty of answers with examples and explanations about the loops, so I won't bother repeating this here. I will add though that the most that I personally have seen do {} while () used is, ironically, not for looping but for this.

Max Langhof
  • 23,383
  • 5
  • 39
  • 72
1

do-while loop performs the task before the condition in while(). It is for situations when you are trying to prompt the same thing for every wrong action (i.e., user authentication, wrong menu entry). On the other hand, a simple while loop performs till a condition is true (Note: In most cases people use for loops instead of while to define counter, initialize, set condition and increment/decrement - all in the same line).

Waqar
  • 8,558
  • 4
  • 35
  • 43
10ZKhaled
  • 134
  • 6