CMPSC 101 Name -
Functions worksheet #5
Trace the following programs. Show the output in a rectangle & trace the values of each variable in a column.
1.
#include <iostream>
using namespace std;
void display(int num);
int main()
{
int num = 0;
int i = 0;
for (i = 0; i < 5; i++)
{
display(i);
cout << endl;
}
return 0;
}// end of main
void display(int num)
{
int j = 0;
for (j = 0; j < num; j++)
{
cout << “*”;
}
}// end of display
2. Assume that the user enters the values 3 and 4.
#include <iostream>
using namespace std;
void showMenu();
void showPrice(int num);
double computeTotal(int number, int num);
int main()
{
int quantity = 0;
int choice = 0;
showMenu();
cout << “Enter choice: “;
cin >> choice;
showPrice(choice);
cout << “How many would you like to buy: “;
cin >> quantity;
cout << “You owe $” << computeTotal(quantity, choice) << endl;
return 0;
}// end of main
void showMenu()
{
cout << “1. apples” << endl;
cout << “2. bananas” << endl;
cout << “3. carrots” << endl;
}// end of showMenu
void showPrice(int num)
{
if (num == 1)
{
cout << “The price of an apple is $1” << endl;
}
else if (num == 2)
{
cout << “The price of a banana is $2” << endl;
}
else
{
cout << “The price of a carrot is $3” << endl;
}
}// end of showPrice
double computeTotal(int number, int num)
{
if (num == 1)
{
return 1 * number;
}
else if (num == 2)
{
return 2 * number;
}
return 3 * number;
}// end of computeTotal