Homework 18

 

1.      Indicate what prints at each comment. Yes, we know that you can just copy and paste this into the compiler and see what output it produces, but you will get a whole lot more out of this if you:

a.       trace the code by hand first, then

b.      compile and run the below with the debugger (keeping a close watch on the control flow and contents of the variables), and finally,

c.       run the compiled program and see if you get the same results as you did when you traced the code by hand.

     #include <iostream>
     using namespace std;

     int confuse(int&,int);
     int main()
     {
        int x, y, z;
        x = 3;
        y = 2;

        cout << "x=" << x << " y=" << y << endl;
        // What is printed by the above line?

        z = confuse(y, x);
        cout << "x=" << x << " y=" << y << " z=" << z << endl;
        // What is printed by the above line?
        return (0);
      }


      int confuse(int& a, int b)
      {
         a = a + b;
         b = 2 * b;
         cout << "b=" << b << " a=" << a << endl;
         // What is printed by the above line?

         return (b);
      }

 

 

2. Midn X and Midn Y are in competition to see who can eat the most hotdogs.  Write a main program that calls the function food and prints out the values returned by food.  Function food should loop 100 times.  Each time through the function’s loop, randomly generate how many hotdogs Midn X ate (between 0 and 3) and how many hotdogs Midn Y ate (between 0 and 3).  Finally the function should return the total number of hotdogs eaten by Midn X and by Midn Y.  Seed the random number generator exactly one time with the clock (using time(0), see below sample program for details on random number generation). You MUST use reference parameters. If you’d like to have a wee bit ‘o fun, replace X and Y with your and your roommates names, we hereby grant you permission to deviate from the specified output in this case.

 

     A sample output is:

 

Here is a sample program that uses random numbers that you may find useful:

// DMN

// randomDemo.cpp

// Program demos how to generate random numbers

 

#include <iostream>

#include <ctime> // needed for time() below

 

using namespace std;

 

int main (){

 

        int randomNum;

        char yesNo;

 

        //Seed the random number generator (just do this once)

        srand(time(0));

 

        cout << "Here are 10 random numbers..." << endl;

        do{

               // generate 10 random numbers between 0..7

               for (int index = 0; index<10; index++)

               {

                       randomNum = rand() % 8;  // range 0..7

                       cout << randomNum << " ";

               } // for

       

               cout << endl << "Would you like 10 more? (y/n):";

               cin >> yesNo;

        } while (yesNo == 'y');

    cout << "Have a fine Navy day!" << endl;

    return 0;

} // main