OOPortal OOPortal
Programming C++  «Prev 

Implementing a for loop

Objective:Rewrite the main() function in the gcd program given below so it uses a for loop instead of a do while loop.


Add a variable named how_many to the program to determine the number of greatest common divisors that will be computed. Use how_many to exit the for loop.

The program

This code is also available in a file named gcdwhile.cpp, which can be found in the compressed course download file page.

//Greatest common divisor program.
#include <iostream.h>  //input/output library
#include <assert.h>    //for errors

int gcd(int m, int n){  //function definition
 int r;                 //declaration of remainder
 while (n != 0) {       //not equal
  r = m % n;            //modulus operator
  m = n;                //assignment
  n = r;
 }                      //end while loop
 return m;              //exit gcd with value m
//end block
int main(){
 int  x, y, g;
 cout << "\nPROGRAM gcd C++";
 do {
   cout << "\nEnter two integers: ";
   cin >> x >> y;
   assert(x * y != 0);      //precondition on gcd 
   cout << "\nGCD(" << x << "," << y << ") = "
   << (g = gcd(x, y)) << endl;
   //postcondition on g
   assert(x % g == 0 &&  y % g == 0);
 } while (x != y);
 return 0;

Paste the source code of your program below and click the Submit button when you are ready to submit this exercise.