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