Repetition in C++

Often we have a specific set of actions we want to repeat over and over: either a fixed number of times or until some condition tells us to stop.

Typical examples might be:

Typically, the set of actions to be repeated is placed within curly brackets, e.g.

    {
        // do this
        // and this
        // and this
        // etc.
    }

The term loop is often used to describe the notion that we perform the set of actions from top to bottom, then "loop" around back to the top to repeat them.

The test for whether or not to repeat the set of actions one more time is placed either at the top or the bottom, giving us the terms top tested loop or bottom tested loop.

The general layout is shown below (without the official C++ syntax for the tests at the top or bottom).

// top tested loop

do we perform the set of actions or skip past the
loop and continue with the rest of the program?
  {
     do this
     and this
     and this
     etc
  }  <= here we go back to the test at the top
// bottom tested loop

  {
     do this
     and this
     and this
     etc
  }  <= here we go back to the test at the top
do we go back to the top to perform the actions again,
or do we drop out of the loop and continue with the 
rest of the program?

Note that bottom tested loops always perform the set of actions at least once, since they don't test to drop out until they get to the bottom of the loop. Top tested loops, on the other hand, could decide on the very first test to skip past the loop - thus the actions inside the loop might never get executed.

There are three types of control statement for repetition in C++: called while loops, do while loops, and for loops.

The do-while loops are bottom tested, the other two are top tested.

while loops

A while loop is a top tested loop with the format

while (condition) 
{
   // actions to repeat if the condition is TRUE
}
The example below prints out all the powers of 10 less than one million:
int power = 1;
while (power < 1000000) {
   printf("%d\n", power);
   power = 10 * power;
}

do-while loops

A do while loop is a bottom tested loop with the format

do {
   // actions to repeat
} while (condition);
Each time the condition evaluates to true it goes back to the top of the loop and runs through the actions one more time;

The example below keeps adding together numbers the user types in until they enter a 0:

float sum = 0;
float userValue;
do {
   printf("Enter a number to add to the total\n");
   printf("   or enter 0 to quit\n");
   scanf("%f", &userValue);
   sum = sum + userValue;
} while (userValue != 0);
printf("The sum was %g\n", sum);

for loops

For loops are a slightly more complex structure, usually used to process a specific set of numeric or character values.

They include an initialization statement, a test condition, and an update statement. For example, the loop below starts variable x at value 1, performs the body of the loop if x's current value is less than or equal to 10, and at the end of each pass through the body of the loop it adds one to x:

int x;
for (x = 1;  x <= 10;  x = x + 1) {
    printf("%d\n", x);
}
This is exactly equivalent to the following while loop:
int x = 1;
while (x <= 10) {
   printf("%d\n", x);
   x = x + 1;
}

Nested loops

We can put loops inside other loops, e.g.

int x = 1;
while (x < 5) {
   int y = 100;;
   while (y < 400) {
      int z = x + y;
      printf("%d, ", z);
      y = y + 100;
   }
   printf("\n";
   x = x + 1;
}
Each time we go through the "outside" loop (the x loop above) we may go through the inside loop multiple times.

In the example above, for each value of x (1, 2, 3, and 4) we go through values 100, 200, and 300 for y. The effect of the code above would be printing

101, 201, 301,
102, 202, 302,
103, 203, 303,
104, 204, 304,

Single-line loops

There is one case in which you may omit the curly brackets around the actions to be repeated: when the actions consist of only a single statement. This is most common with simple for loops or simple while loops, for example:

int i;
for (i = 0; i < 10; i++) 
    printf("%d\n", i);  // the for loop body is just one statement

while (x < y)
    x = x * 2;  // the while loop body is just one statement

Infinite loops

One of the problems with loops is ensuring our test condition can and does eventually stop the loop.

Loops that never stop are called infinite loops, and the only way to interrupt them is to kill the program (done in linux by holding down the control key and pressing c).

Common causes of infinite loops include:


Further discussion

Iteration is simply the repetition of a group of commands a certain number of times, and is the second major form of program control we consider.

Repetition: the purpose of loops

Types of loops

For loops: syntax and parts

Repetition until a condition is met

While loops

While loop examples

Infinite loops

Sentinels as exit conditions

Do-while loops

Data validation

Common loops errors

Full example

Calculates the sum of the squares of all integers from a lower bound the user enters to an upper bound the user enters.
#include <cstdio>
using namespace std;

int sumsquares(int lower, int upper);

int main()
{
   int low, high, result;

    do {
       printf("Please enter two integers,");
       printf(" low number first\n");
       scanf("%d %d", &low, &high);
    } while (low > high);

    result = sumsquares(low, high);

    printf("The sum of the squares of values ");
    printf("%d through %d is ", low, high);
    printf("%d\n", result);
}

int sumsquares(int lower, int upper)
{
   int sumsquares = 0;
   for (int index=lower; index<=upper; index++) {
       sumsquares += (index * index);
   }
   return(sumsquares);
}

Basic loop summary

Nested loops

Flow of control

Characters in loops

Mixing types of loops

Mixing loops and other structures

Using functions to simplify things

Mixing loops and other structures

Simplified version

int main()
{  
   char cmd;
   bool quit = false;
   int count = 0;

   while (!quit) {
   
      print_prompt();  // prints out the menu
      scanf("%c", &cmd);
                       
      switch (cmd) {
          case 'e':
          case 'E': even_num(count);
                    break;
          case 'n':
          case 'N': question_num(count);
                    break;
          case 'q';
          case 'Q': quit = true; 
                    break;
          default: printf("Invalid command\n");
      }
   }
}

void even_num(int &c)
{
    int number;
    printf("Please enter your number\n");
    scanf("%d", &number);
    printf("%d is ", number);
    if ((number % 2) == 1) printf("not");
    printf(" even\n");
    c++;
}

void question_num(int &c)
{
    c++;
    printf("This is valid question number");
    printf("%d\n", c);
}

More examples