REPEATING A BLOCK OF STATEMENTS

The capability to repeat a group of statements is fundamental to most applications. Without this, an organization would need to modify the payroll program every time an extra employee was hired, and you would need to reload your favorite game every time you wanted to play. So, let’s first understand how a loop works.

What Is a Loop?

A loop executes a sequence of statements subject to a given condition. You can write a loop with the statements that you have met so far. You just need an if and the dreaded goto. Look at the following example:

// Ex3_07.cpp
// Creating a loop with an if and a goto
#include <iostream>
        
using std::cout;
using std::endl;
        
int main()
{
   int i(1), sum(0);
   const int max(10);
        
loop:
   sum += i;             // Add current value of i to sum
   if(++i <= max)
      goto loop;         // Go back to loop until i = 11
        
   cout << endl
        << "sum = " << sum << endl
        << "i = "   << i   << endl;
   return 0;
}

This example accumulates the sum of integers from 1 to 10. The first time through the sequence of statements, i has the initial value 1 and is added to sum, which starts out as zero. In the if, i is incremented to 2 and, as long as it is less than or equal to max, the unconditional branch to loop occurs, and the value of i, now 2, is added to sum. This continues with i being incremented and added to sum each time, until finally, when i is incremented to 11 in the if, the branch back is not executed. If you run this example, you get the following output:

sum = 55
i = 11

This shows ...

Get Ivor Horton's Beginning Visual C++ 2012 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.