CSC 306 Introduction to Programming with C++

Introduction to Looping Structures

Chapter 2.4 (pages 74-82)


Objectives

Important Definitions


Example of Finding Averages

Suppose we have four test scores, and you want to compute the average. You can use the following C++ program computes that average.
#include <iostream>
using namespace std;

// This program reads and compute the average of 3 integers.

int main() { 

  int num1, num2, num3, num4; // numbers to average
  double average;

  // prompt the user for the four scores 
  cout << "Enter three grades separated by spaces, then press 'Enter':" << endl; 

  // read and store four integers (the space in between them allows this syntax 
  cin >> num1 >> num2 >> num3 >> num4;

  // Calculate the average (note 4.0 is used to prevent integer division)
  average = (num1 + num2 + num3 + num4)/4.0;

  // Display the average
  cout << "The average is " << average << endl; 

  return 0;
} 

We could make simple changes to the program to compute the average of six numbers instead, in which after asking the user for six numbers, the line to find the average is:

  average = (num1 + num2 + num3 + num4 + num5 + num6)/6.0;
However, imagine using this technique to compute the average of 1000 numbers; the code would be very tedious and error-prone as it would be easy to forget a number. A better approach would be to use a loop construct that executes a portion of the code for multiple iterations. A loop is a programming structure that executes repeatedly while the loop condition is true. An iteration is one pass through the execution of the code inside the loop, including the evaluation of the condition.

An Example of a while Loop

Here is a new version of the above program written using a while loop. The major changes to our code will made in the lines that are marked with comments.
#include  
using namespace std; 
//Program to read and average 6 integers using a while loop, 

int main(void) {
  int num; 
  int count;   // use this variable to keep track of the number of grades
  int sum = 0; // initialize the sum to 0
  double average; 

  cout << "Enter six grades separated by a single space, then press : "; 

  // Repeatedly inputs grades and add them to sum, where count ensures 6 entries 
  count = 1; // initialize the variable count to 1
  while( count <= 6) {
    // read each number and add it to the sum: 
    cin >> num; 
    sum = sum + num; 
    count++;  // update the count 
  } 

  cout << endl;  // to make it look better, output a newline

  average = sum/6.0;  // compute the average, total divided by the number of grades 
  cout << "The average is " << average << endl; 

  return 0; 
} 
The syntax for a while loop is:
while( Boolean_Expression ) { 
    Statement 1; 
    Statement 2; 
    ... 
    Statement Last; 
} 
The statements between { and } is in what is called the body of the loop. Notice that the loop body in the example above executes when count = 1,2,3,4,5,6 and stops when count has the value 7 because it is then no longer less than or equal to six. If the boolean condition is false right before the loop starts, the body executes 0 times; in the example above, this would be true if count was greater than six. Sometimes, you may want to execute the loop body at least once regardless of the value in the counter variable. In such a case you have to use a do while loop. The syntax for this kind of loop is:
do { 
    Statement 1; 
    Statement 2; 
    ... 
    Statement Last; 
} while( Boolean_Expression ); 

The do while loop is the appropriate choice when you always want to be certain to go through your loop at least once.

Types of C++ Loops

There are two types of loops. The first type is controlled by a counter variable and is referred to as a count-controlled loop. The second type is controlled by a particular event and is referred to as an event-controlled loop. The above example uses a count-controlled while loop. However, in C++ it is more typical to use a for-loop as a count controlled loop, as shown in the following code fragment where the while loop is replaced by a for loop:
  // The for-loop is always controlled by a counter variable. The loop parts are:
  // 1) initialize the count variable to start with 1 (this is only done once)
  // 2) check to see if count is still <= 6
  // 3) execute the loop body if the condition is true
  // 4) increment (add one to) count
  for (count = 1; count<=6; count++) { 
    cin >> num; 
    sum = sum + num; 
    // (*) updating the count is done automatically in the for-loop
    } 
Note that both the for and while loops are equivalent.

In both count-controlled and event-controlled types of loop, there is always a Boolean expression that leads the flow of the computation into the body of the loop or out of it. To explain the difference between these two types of loops, consider the following two applications:

If you wish to have a good working loop, there are three things that you have to always remember to insert:

  1. initialization: Be sure that the variable that controls the loop has a valid value. Otherwise, the loop can start with a garbage value and may result in unpredictable behavior.
  2. condition check: the Boolean expression must correctly check the controlling variable to determine if the loop body repeats.
  3. change: The controlling variable must change inside the loop so that the condition check will eventually evaluate to false. If the condition does not change in the body of the loop, then the loop condition will check the exact same thing an infinite number of times and you will have what is called an infinite loop. You will have to terminate your program in this case using Ctrl-C.

Note that while and do-while loops are typically used for event-controlled loops and for-loops are typically used for count-controlled loops in C++. The for-loop is not covered in your text until a later chapter, but I thought you might like to see it now. You will not need it for this assignment.


Assignment Details

This assignment must be completed individually.

The greatest common divisor (GCD) of two non-zero integers is the largest integer that divides both of them evenly (without a remainder). Euclid's algorithm for computing the GCD was described in the Elements of Euclid (circa 300 B. C. E.) and depends on the fact that the GCD of any two numbers A and B (with A not less than B) is the same as the GCD of the B and the remainder resulting from A divided by B.

Here's an example of using Euclid's algorithm where A=2322 and B=654:
2322 = 654*3 + 360 gcd(2322, 654) = gcd(654, 360)
654 = 360*1 + 294 gcd(654, 360) = gcd(360, 294)
360 = 294*1 + 66 gcd(360, 294) = gcd(294, 66)
294 = 66*4 + 30 gcd(294, 66) = gcd(66, 30)
66 = 30*2 + 6 gcd(66, 30) = gcd(30, 6)
30 = 6*5 gcd(30, 6) = 6
When the remainder of the next integer division is 0 you stop, and the gcd(2322, 654) = 6.

This algorithm can be performed with just repeated use of % for integers. You will need a while loop, because to use this algorithm, you need to repeatedly find these remainders, and you will not know in advance how many times you will need to go through the loop.

Here are some other facts about GCDs that you might find useful:
GCD(0, 0) = 0
GCD(a, b) = GCD(b, a)
GCD(a, b) = GCD(-a, b)
GCD(a, 0) = | a |

What you need to do:

Your task is to write a program in a file called YourlastName_306A4.cpp that 1) prompts the user for two integers, 2) uses Euclid's Algorithm to find their GCD, and 3) output this value. Some pointers: When you are finished with your assignment, drop your source code into the CSC306_A04 dropbox on the Academic server.


Back to Introduction to Computer Programming with C++ Homepage