The do-while loop

The do-while loop

Its format is:

do statement while (condition);

Its practicality is strictly identical with the while loop, except that condition within the do-while loop is evaluated when the execution of statement rather than before, granting a minimum of one execution of statement even though condition is never concluded. For instance, the subsequent example program prints any number you enter till you enter zero.

// number print

#include <iostream>

using namespace std;

int main ()

{

unsigned long numbers;

do {

cout << “Enter number (0 to end): “;

cin >> numbers;

cout << “You entered: ” << numbers <<std::endl;

} while (numbers != 0);

return 0;

}

Output

Enter number (0 to end): 12345

You entered: 12345

Enter number (0 to end): 160277

You entered: 160277

Enter number (0 to end): 0

You entered: 0

The do-while loop is typically used once the condition that has got to confirm the terminating condition value of the loop is decided among the loop statement itself, like within the previous case, wherever the user input inside the block is what’s used to determine if the loop has got to finish. In reality if you ne’er enter the value zero within the previous example you’ll be prompted for a lot of numbers forever.

PDF is available here The do while loop

The while loop

The while loop

Loops have as purpose to repeat a message up to an explicit range of times or whereas a condition is achieved.

Its format is:

while (expression) statement

and its practicality is solely to repeat statement whereas the condition set in expression is true. For example, we will create a program to count backward employing a while-loop:

// custom countdown using while

#include <iostream>

using namespace std;

int main ()

{

int num;

cout << “Enter the starting number > “;

cin >> num;

while (num>0) {

cout << num << “, “;

–num;

}

cout << “FIRE!”;

return 0;

}

Output

Enter the starting number > 8

8, 7, 6, 5, 4, 3, 2, 1, FIRE!

When the program starts the user is prompted to a number to start the counting back. Then the while loop begins, if the value entered by the user fulfills the condition num>0 (that num is bigger than zero) the block that follows the condition will run and keep on executing until the condition (num>0) remains being true.

The whole method of the previous program are often taken in keeping with the subsequent script (beginning in main):

  1. User assigns a value to num
  2. The while condition is checked (num>0). At this time there 2 posibilities:

* condition is true: statement is executed (to step 3)

* condition is false: ignore statement and continue  (to step 5)

  1. Execute statement:

cout << num << “, “;

–num;

(prints the value of num on the screen and reduces num by 1)

  1. finish of block. come back mechanically to step two
  2. Continue the program right when the block: print FIRE! and finish program.

Get PDF of Iteration structures—while loop