Homework 18

1.     Using the code below, do the following

a.      Print the code out.

b.     Trace the execution of the code by hand.  Draw appropriate pictures to keep track of all the variables involved.

c.      At each point where a comment asks “What is printed…”, write down what is printed by that line of code.

d.     After all this, compile and run the program.  Do your predictions match what actually happened?  If not, try to figure out why (if possible, modify your picture *and* predictions to match the actual behavior.).

e.      Turn in the code, with your picture and predictions.

#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 <cstdlib> // needed for rand() and srand() below

#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