C++ How to Program: Solutions

3.12 A parking garage charges a $2.00 minimum fee to park for up to three hours. The garage charges an additional $0.50 per
hour for each hour or part thereof in excess of three hours. The maximum charge for any given 24-hour period is $10.00. Assume
that no car parks for longer than 24 hours at a time. Write a program that will calculate and print the parking charges for each of 3
customers who parked their cars in this garage yesterday. You should enter the hours parked for each customer. Your program
should print the results in a neat tabular format and should calculate and print the total of yesterday’s receipts. The program should
use the function calculate Charges to determine the charge for each customer. Your outputs should appear in the following
format:




 // Exercise 3.12 Solution
 #include <iostream>

using std::cout;
 using std::endl;
 using std::cin;
 using std::ios;

#include <iomanip>

 using std::setw;
using std::setprecision;
using std::setiosflags;

#include <cmath>

double calculateCharges( double );

 main()
 {
 double hour, currentCharge, totalCharges = 0.0, totalHours = 0.0;
 int first = 1;

 cout << "Enter the hours parked for 3 cars: ";

 for ( int i = 1; i <= 3; i++ ) {
 cin >> hour;
 totalHours += hour;

 if ( first ) {
 cout << setw( 5 ) << "Car" << setw( 15 ) << "Hours"
 << setw( 15 ) << "Charge\n";
 first = 0; // prevents this from printing again
 }

 totalCharges += ( currentCharge = calculateCharges( hour ) );
 cout << setiosflags( ios::fixed | ios::showpoint )
 << setw( 3 ) << i << setw( 17 ) << setprecision( 1 ) << hour
 << setw( 15 ) << setprecision( 2 ) << currentCharge << "\n";
 }

 cout << setw( 7 ) << "TOTAL" << setw( 13 ) << setprecision( 1 )
 << totalHours << setw( 15 ) << setprecision( 2 )
 << totalCharges << endl;


 return 0;
 }

 double calculateCharges( double hours )
 {
 double charge;

 if ( hours < 3.0 )
 charge = 2.0;
 else if ( hours < 19.0 )
 charge = 2.0 + .5 * ceil( hours - 3.0 );
 else
 charge = 10.0;

 return charge;
}
3.13 An application of function floor is rounding a value to the nearest integer. The statement y = floor( x + .5 ); will round the number x to the nearest integer and assign the result to y. Write a program that reads several numbers and uses the preceding statement to round each of these numbers to the nearest integer. For each number processed, print both the original number and the rounded number.

// Exercise 3.13 Solution
 #include <iostream>

using std::cout;
using std::endl;
using std::cin;
using std::ios;

#include <iomanip>

using std::setprecision;
using std::setiosflags;

#include <cmath>

void roundToIntegers( void );

int main()
{
roundToIntegers();

return 0;
}

void roundToIntegers( void )
{
double x, y;

cout << setiosflags( ios::fixed | ios::showpoint );

 for ( int loop = 1; loop <= 5; loop++ ) {
 cout << "Enter a number: ";
 cin >> x;
 y = floor( x + .5 );
 cout << x << " rounded is " << setprecision( 1 ) << y << endl;
 }
 }

3.14 Function floor can be used to round a number to a specific decimal place. The statement y = floor( x * 10 + .5 ) / 10; rounds x to the tenths position (the first position to the right of the decimal point). The statement y = floor( x * 100 + .5 ) / 100; rounds x to the hundredths position (the second position to the right of the decimal point). Write a program that defines four functions to round a number x in various ways: a) roundToInteger( number ) b) roundToTenths( number ) c) roundToHundredths( number ) d) roundToThousandths( number ) For each value read, your program should print the original value, the number rounded to the nearest integer, the number rounded to the nearest tenth, the number rounded to the nearest hundredth and the number rounded to the nearest thousandth.


 // Exercise 3.14 Solution
 #include <iostream>

 using std::cout;
 using std::cin;
 using std::ios;

#include <iomanip>

 using std::setprecision;
 using std::setiosflags;
 using std::resetiosflags;

 #include <cmath>

 double roundToInteger( double );
 double roundToTenths( double );
 double roundToHundreths( double );
 double roundToThousandths( double );

 int main()
 {
 int count;
 double number;

 cout << "How many numbers do you want to process? "
 << setiosflags( ios::fixed );
 cin >> count;

 for ( int i = 0; i < count; ++i ) {
 cout << "\nEnter number: ";
 cin >> number;
 cout << number << " rounded to the nearest integer is: "
 << setprecision( 0 ) << roundToInteger( number ) << '\n'
 << setiosflags( ios::showpoint )
 << number << " rounded to the nearest tenth is: "
 << setprecision( 1 ) << roundToTenths( number ) << '\n'
 << number << " rounded to the nearest hundredth is: "
 << setprecision( 2 ) << roundToHundreths( number ) << '\n'
 << number << " rounded to the nearest thousandth is: "
 << setprecision( 3 ) << roundToThousandths( number ) << '\n'
 << resetiosflags( ios::showpoint );
 }

 return 0;
 }

 double roundToInteger( double n )
 {
 return floor( n + .5 );
 }

 double roundToTenths( double n )
 {
 return floor( n * 10 + .5 ) / 10;
 }

 double roundToHundreths( double n )
 {
 return floor( n * 100 + .5 ) / 100;
 }

 double roundToThousandths( double n )
 {
 return floor( n * 1000 + .5 ) / 1000.0;
 }

3.18 Write a function integerPower( base, exponent ) that returns the value of base exponent For example, integerPower( 3, 4 ) = 3 * 3 * 3 * 3. Assume that exponent is a positive, nonzero integer and that base is an integer. The function integerPower should use for or while to control the calculation. Do not use any math library functions.


 // Exercise 3.18 Solution
 #include <iostream>

using std::cout;
 using std::endl;
 using std::cin;

int integerPower( int, int );

 int main()
 {
 int exp, base;

 cout << "Enter base and exponent: ";
 cin >> base >> exp;
 cout << base << " to the power " << exp << " is: "
 << integerPower( base, exp ) << endl;

 return 0;
 }

 int integerPower( int b, int e )
 {
 int product = 1;

 for ( int i = 1; i <= e; ++i )
 product *= b;

 return product;
 }


3.19 Define a function hypotenuse that calculates the length of the hypotenuse of a right triangle when the other two sides are given. Use this function in a program to determine the length of the hypotenuse for each of the following triangles. The function should take two arguments of type double and return the hypotenuse as a double.


 // Exercise 3.19 Solution
 #include <iostream>

using std::cout;
 using std::endl;
 using std::cin;
 using std::ios;

#include <iomanip>

 using std::setprecision;
 using std::setiosflags;

 #include <cmath>

 double hypotenuse( double, double );

 int main()
 {
 double side1, side2;

 cout << setiosflags( ios::fixed | ios::showpoint );

 for ( int i = 1; i <= 3; ++i ) {
 cout << "\nEnter 2 sides of right triangle: ";
 cin >> side1 >> side2;
 cout << "Hypotenuse: " << setprecision( 1 )
 << hypotenuse( side1, side2 ) << endl;
 }

 return 0;
 }

 double hypotenuse( double s1, double s2 )
 {
 return sqrt( s1 * s1 + s2 * s2 );
 }


3.20 Write a function multiple that determines for a pair of integers whether the second integer is a multiple of the first. The function should take two integer arguments and return true if the second is a multiple of the first, false otherwise. Use this function in a program that inputs a series of pairs of integers.

 // Exercise 3.20 Solution
 #include <iostream>

using std::cout;
 using std::endl;
 using std::cin;

bool multiple( int, int );

 int main()
 {
 int x, y;

 for ( int i = 1; i <= 3; ++i ) {
 cout << "Enter two integers: ";
 cin >> x >> y;

 if ( multiple( x, y ) )
 cout << y << " is a multiple of " << x << "\n\n";
 else
 cout << y << " is not a multiple of " << x << "\n\n";
 }

 cout << endl;

 return 0;
 }

 bool multiple( int a, int b )
 {
 return !( b % a );
 }


3.21 Write a program that inputs a series of integers and passes them one at a time to function even, which uses the modulus operator to determine whether an integer is even. The function should take an integer argument and return true if the integer is even and false otherwise.



 // Exercise 3.21 Solution
 #include <iostream>

using std::cout;
 using std::endl;
 using std::cin;

bool even( int );

 int main()
 {
 int x;

 for ( int i = 1; i <= 3; ++i ) {
 cout << "Enter an integer: ";
 cin >> x;

 if ( even( x ) )
 cout << x << " is an even integer\n\n";
 else
 cout << x << " is an odd integer\n\n";
 }

 cout << endl;

 return 0;
 }

 bool even( int a )
 {
 return !( a % 2 );
 }
3.22 Write a function that displays at the left margin of the screen a solid square of asterisks whose side is specified in integer parameter side. For example, if side is 4, the function displays.


 // Exercise 3.22 Solution
 #include <iostream>

using std::cout;
 using std::endl;
 using std::cin;

void square( int );

 int main()
 {
 int side;

 cout << "Enter side: ";
 cin >> side;
 cout << '\n';

 square( side );

 cout << endl;

 return 0;
 }

 void square( int s )
 {
 for ( int row = 1; row <= s; ++row ) {

 for ( int col = 1; col <= s; ++col )
 cout << '*';

 cout << '\n';
 }
 }
3.23 Modify the function created in Exercise 3.22 to form the square out of whatever character is contained in character parameter fillCharacter. Thus, if side is 5 and fillCharacter is “#,” then this function should print.


 // Exercise 3.23 Solution
 #include <iostream>

using std::cout;
 using std::endl;
 using std::cin;

void square( int, char );

 int main()
 {
 int s;
 char c;

 cout << "Enter a character and the side length: ";
 cin >> c >> s;
 cout << '\n';

 square( s, c );

 cout << endl;

 return 0;
 }

 void square( int side, char fillCharacter )
 {
 for ( int row = 1; row <= side; ++row ) {

 for ( int col = 1; col <= side; ++col )
 cout << fillCharacter;

 cout << '\n';
 }
 }

3.25 Write program segments that accomplish each of the following: a) Calculate the integer part of the quotient when integer a is divided by integer b. b) Calculate the integer remainder when integer a is divided by integer b. c) Use the program pieces developed in a) and b) to write a function that inputs an integer between 1 and 32767 and prints it as a series of digits, each pair of which is separated by two spaces. For example, the integer 4562 should be printed as 4 5 6 2

 // Exercise 3.25 Solution
 #include <iostream>

using std::cout;
 using std::endl;
 using std::cin;

#include <iomanip>

 using std::setw;

 int quotient( int, int );
 int remainder( int, int );

 int main()
 {
 int number, divisor = 10000;

 cout << "Enter an integer between 1 and 32767: ";
 cin >> number;

 cout << "The digits in the number are:\n";

 while ( number >= 1 ) {

 if ( number >= divisor ) {
 cout << setw( 3 ) << quotient( number, divisor );
 number = remainder( number, divisor );
 divisor = quotient( divisor, 10 );
 }
 else
 divisor = quotient( divisor, 10 );
 }

 cout << endl;

 return 0;
 }

 // Part A: determine quotient using integer division
 int quotient( int a, int b )
 {
 return a / b;
 }

 // Part B: determine remainder using the modulus operator
 int remainder( int a, int b )
 {
 return a % b;
 }

3.26 Write a function that takes the time as three integer arguments (for hours, minutes and seconds), and returns the number of seconds since the last time the clock “struck 12.” Use this function to calculate the amount of time in seconds between two times, both of which are within one 12-hour cycle of the clock.

 // Exercise 3.26 Solution
 #include <iostream>

using std::cout;
 using std::endl;
 using std::cin;

unsigned seconds( unsigned, unsigned, unsigned );

 int main()
 {
 unsigned hours, minutes, secs, temp;

 cout << "Enter the first time as three integers: ";
 cin >> hours >> minutes >> secs;

 temp = seconds( hours, minutes, secs );

 cout << "Enter the second time as three integers: ";
 cin >> hours >> minutes >> secs;

 cout << "The difference between the times is "
 << seconds( hours, minutes, secs ) - temp
 << " seconds" << endl;

 return 0;
 }

 unsigned seconds( unsigned h, unsigned m, unsigned s )
 {
 return 3600 * ( h >= 12 ? h - 12 : h ) + 60 * m + s;
 }




3.27 Implement the following integer functions:
a) Function celsius returns the Celsius equivalent of a Fahrenheit temperature.
b) Function fahrenheit returns the Fahrenheit equivalent of a Celsius temperature.
c) Use these functions to write a program that prints charts showing the Fahrenheit equivalents of all Celsius temperatures
from 0 to 100 degrees, and the Celsius equivalents of all Fahrenheit temperatures from 32 to 212 degrees. Print the outputs
in a neat tabular format that minimizes the number of lines of output while remaining readable.



 // Exercise 3.27 Solution
 #include <iostream>

using std::cout;
 using std::endl;

int celcius( int );
 int fahrenheit( int );

 int main()
 {
 cout << "Fahrenheit equivalents of Celcius temperatures:\n"
 << "Celcius\t\tFahrenheit\n";

 for ( int i = 0; i <= 100; ++i )
 cout << i << "\t\t" << fahrenheit( i ) << '\n';

 cout << "\nCelcius equivalents of Fahrenheit temperatures:"
 << "\nFahrenheit\tCelcius\n";

 for ( int j = 32; j <= 212; ++j )
 cout << j << "\t\t" << celcius( j ) << '\n';

 cout << endl;

 return 0;
 }

 int celcius( int fTemp )
 {
 return static_cast< int > ( 5.0 / 9.0 * ( fTemp - 32 ) );
 }

 int fahrenheit( int cTemp )
 {
 return static_cast< int > ( 9.0 / 5.0 * cTemp + 32 );
 }

3.28 Write a function that returns the smallest of three double-precision, floating-point numbers.

 // Exercise 3.28 Solution
 #include <iostream>
 using std::cout;
 using std::endl;
 using std::cin;

double smallest3( double, double, double );

int main()
 {
 double x, y, z;

 cout << "Enter three numbers: ";
 cin >> x >> y >> z;
 cout << "The smallest value is " << smallest3( x, y, z ) << endl;

 return 0;
 }

 double smallest3( double smallest, double b, double c )
 {
 if ( b < smallest && c > smallest )
 return b;
 else if ( c < smallest )
 return c;
 else
 return smallest;
 }




3.29 An integer number is said to be a perfect number if the sum of its factors, including 1 (but not the number itself), is equal
to the number. For example, 6 is a perfect number, because 6 = 1 + 2 + 3. Write a function perfect that determines whether parameter
number is a perfect number. Use this function in a program that determines and prints all the perfect numbers between 1
and 1000. Print the factors of each perfect number to confirm that the number is indeed perfect. Challenge the power of your computer
by testing numbers much larger than 1000.




 // Exercise 3.29 Solution
 #include <iostream>

using std::cout;
 using std::endl;

bool perfect( int );

int main()
 {
 cout << "For the integers from 1 to 1000:\n";

 for ( int j = 2; j <= 1000; ++j )
 if ( perfect( j ) )
 cout << j << " is perfect\n";

 cout << endl;

 return 0;
 }

 bool perfect( int value )
 {
 int factorSum = 1;

 for ( int i = 2; i <= value / 2; ++i )
 if ( value % i == 0 )
 factorSum += i;

 return factorSum == value ? true : false;
 }


3.30 An integer is said to be prime if it is divisible by only 1 and itself. For example, 2, 3, 5 and 7 are prime, but 4, 6, 8 and 9 are not. a) Write a function that determines whether a number is prime. b) Use this function in a program that determines and prints all the prime numbers between 1 and 10,000. How many of these 10,000 numbers do you really have to test before being sure that you have found all the primes? c) Initially, you might think that n/2 is the upper limit for which you must test to see whether a number is prime, but you need only go as high as the square root of n. Why? Rewrite the program, and run it both ways. Estimate the performance improvement.

 // Exercise 3.30 Part A Solution
 #include <iostream>
 using std::cout;

#include <iomanip>

using std::setw;

bool prime( int );

 int main()
 {
 int count = 0;

 cout << "The prime numbers from 1 to 10000 are:\n";

 for ( int loop = 2; loop <= 10000; ++loop )
 if ( prime( loop ) ) {
 ++count;
 cout << setw( 6 ) << loop;

 if ( count % 10 == 0 )
 cout << '\n';
 }

 return 0;
 }

 bool prime( int n )
 {
 for ( int loop2 = 2; loop2 <= n / 2; loop2++ )
 if ( n % loop2 == 0 )
 return false;

 return true;
 }


 // Exercise 3.30 Part C Solution
 #include <iostream>

using std::cout;

#include <iomanip>
 using std::setw;

#include <cmath>

 bool prime( int n );

 int main()
 {
 int count = 0;

 cout << "The prime numbers from 1 to 10000 are:\n";

 for ( int j = 2; j <= 10000; ++j )
 if ( prime( j ) ) {
 ++count;
 cout << setw( 5 ) << j;

 if ( count % 10 == 0 )
 cout << '\n';
 }

 return 0;
 }

 bool prime( int n )
 {
 for ( int i = 2; i <= static_cast< int > ( sqrt( n ) ); ++i )
 if ( n % i == 0 )
 return false;

 return true;
 }

3.31 Write a function that takes an integer value and returns the number with its digits reversed. For example, given the number 7631, the function should return 1367.



 // Exercise 3.31 Solution
 #include <iostream>

 using std::cout;
 using std::endl;
 using std::cin;

#include <iomanip>

 using std::setw;
 using std::setfill;

 int reverseDigits( int );
 int width( int );

 int main()
 {
 int number;

 cout << "Enter a number between 1 and 9999: ";
 cin >> number;

 cout << "The number with its digits reversed is: "
 << setw( ( width( number ) ) ) << setfill( '0' )
 << reverseDigits( number )
 << endl;

 return 0;
 }

 int reverseDigits( int n )
 {
 int reverse = 0, divisor = 1000, multiplier = 1;

 while ( n > 10 ) {

 if ( n >= divisor ) {
 reverse += n / divisor * multiplier;
 n %= divisor;
 divisor /= 10;
 multiplier *= 10;
 }
 else
 divisor /= 10;
 }

 reverse += n * multiplier;
 return reverse;
 }

 int width( int n )
 {
 if ( n /= 1000 )
 return 4;
 else if ( n /= 100 )
 return 3;
 else if ( n /= 10 )
 return 2;
 else
 return 1;
 }
3.32 The greatest common divisor (GCD) of two integers is the largest integer that evenly divides each of the numbers. Write a function gcd that returns the greatest common divisor of two integers.


 // Exercise 3.32 Solution
 #include <iostream>

using std::cout;
 using std::cin;

int gcd( int, int );

int main()
 {
 int a, b;

 for ( int j = 1; j <= 5; ++j ) {
 cout << "Enter two integers: ";
 cin >> a >> b;
 cout << "The greatest common divisor of " << a << " and "
 << b << " is " << gcd( a, b ) << "\n\n";
 }

 return 0;
 }

 int gcd( int x, int y )
 {
 int greatest = 1;

 for ( int i = 2; i <= ( ( x < y ) ? x: y ); ++i )
 if ( x % i == 0 && y % i == 0 )
 greatest = i;

 return greatest;
}



3.33 Write a function qualityPoints that inputs a student’s average and returns 4 if a student's average is 90–100, 3 if the average is 80–89, 2 if the average is 70–79, 1 if the average is 60–69 and 0 if the average is lower than 60.


 // Exercise 3.33 Solution
 #include <iostream>

using std::cout;
 using std::endl;
 using std::cin;

int qualityPoints( int );

 int main()
 {
 int average;

 for ( int loop = 1; loop <= 5; ++loop ) {
 cout << "\nEnter the student's average: ";
 cin >> average;
 cout << average << " on a 4 point scale is "
 << qualityPoints( average ) << '\n';
 }

 cout << endl;
 return 0;
 }

 int qualityPoints( int average )
 {
 if ( average >= 90 )
 return 4;
 else if ( average >= 80 )
 return 3;
 else if ( average >= 70 )
 return 2;
 else if ( average >= 60 )
 return 1;
 else
 return 0;
 }

3.34 Write a program that simulates coin tossing. For each toss of the coin, the program should print Heads or Tails. Let the program toss the coin 100 times and count the number of times each side of the coin appears. Print the results. The program should call a separate function flip that takes no arguments and returns 0 for tails and 1 for heads. Note: If the program realistically simulates the coin tossing, then each side of the coin should appear approximately half the time.

 // Exercise 3.34 Solution

#include <iostream>

using std::cout;
 using std::endl;

#include <cstdlib>
 #include <ctime>

 int flip( void );

 int main()
 {
 int headCount = 0, tailCount = 0;

 srand( time( 0 ) );

 for ( int loop = 1; loop <= 100; loop++ ) {

 if ( flip() == 0 ) {
 tailCount++;
 cout << "Tails ";
 }
 else {
 headCount++;
 cout << "Heads ";
 }

 if ( loop % 10 == 0 )
 cout << '\n';
 }

 cout << "\nThe total number of Heads was "
 << headCount << "\nThe total number of Tails was "
 << tailCount << endl;

 return 0;
 }

 int flip( void )
 {
 return rand() % 2;
 }


3.35 Computers are playing an increasing role in education. Write a program that will help an elementary school student learn multiplication. Use rand to produce two positive one-digit integers. It should then type a question such as: How much is 6 times 7? The student then types the answer. Your program checks the student's answer. If it is correct, print "Very good!", and then ask another multiplication question. If the answer is wrong, print "No. Please try again." and then let the student try the same question again repeatedly until the student finally gets it right.

// Exercise 3.35 Solution
#include <iostream>

using std::cout;
 using std::endl;
 using std::cin;

#include <cstdlib>
 #include <ctime>

 void multiplication( void );

 int main()
 {
 srand( time( 0 ) );
 multiplication();
 return 0;
 }

 void multiplication( void )
 {
 int x, y, response = 0;

 cout << "Enter -1 to End.\n";

 while ( response != -1 ) {
 x = rand() % 10;
 y = rand() % 10;

 cout << "How much is " << x << " times " << y << " (-1 to End)? ";
 cin >> response;

 while ( response != -1 && response != x * y ) {
 cout << "No. Please try again.\n? ";
 cin >> response;
 }

 if ( response != -1 )
 cout << "Very good!\n\n";
 }

 cout << "That's all for now. Bye." << endl;
 }


3.36 The use of computers in education is referred to as computer-assisted instruction (CAI). One problem that develops in CAI environments is student fatigue. This can be eliminated by varying the computer's dialogue to hold the student's attention. Modify the program of Exercise 3.35 so the various comments are printed for each correct answer and each incorrect answer as follows: Responses to a correct answer Very good! Excellent! Nice work! Keep up the good work! Responses to an incorrect answer No. Please try again. Wrong. Try once more. Don't give up! No. Keep trying. Use the random number generator to choose a number from 1 to 4 to select an appropriate response to each answer. Use a switch structure to issue the responses.


 // Exercise 3.36 Solution
 #include <iostream>

using std::cout;
 using std::endl;
 using std::cin;

#include <cstdlib>
 #include <ctime>

 void correctMessage( void );
 void incorrectMessage( void );
 void multiplication( void );

 int main()
 {
 srand( time( 0 ) );
 multiplication();

 return 0;
 }

 void correctMessage( void )
 {
 switch ( rand() % 4 ) {
 case 0:
 cout << "Very good!";
 break;
 case 1:
 cout << "Excellent!";
 break;
 case 2:
 cout << "Nice work!";
 break;
 case 3:
 cout << "Keep up the good work!";
 break;
 }

 cout << "\n\n";
 }

 void incorrectMessage( void )
 {
 switch ( rand() % 4 ) {
 case 0:
 cout << "No. Please try again.";
 break;
 case 1:
 cout << "Wrong. Try once more.";
 break;
 case 2:
 cout << "Don't give up!";
 break;
 case 3:
 cout << "No. Keep trying.";
 break;
 }

 cout << "\n? ";
 }

 void multiplication( void )
 {
 int x, y, response = 0;

 while ( response != -1 ) {
 x = rand() % 10;
 y = rand() % 10;

 cout << "How much is " << x << " times " << y
 << " (-1 to End)? ";
 cin >> response;

 while ( response != -1 && response != x * y ) {
 incorrectMessage();
 cin >> response;
 }

 if ( response != -1 ) {
 correctMessage();
 }
 }

 cout << "That's all for now. Bye." << endl;
 }


3.37 More sophisticated computer-aided instruction systems monitor the student’s performance over a period of time. The decision to begin a new topic is often based on the student’s success with previous topics. Modify the program of Exercise 3.36 to count the number of correct and incorrect responses typed by the student. After the student types 10 answers, your program should calculate the percentage of correct responses. If the percentage is lower than 75 percent, your program should print "Please ask your instructor for extra help" and then terminate.

 // Exercise 3.37 Solution
 #include <iostream>

using std::cout;
 using std::endl;
 using std::cin;

#include <cstdlib>
 #include <ctime>

 void multiplication( void );
 void correctMessage( void );
 void incorrectMessage( void );

 int main()
 {
 srand( time( 0 ) );
 multiplication();

 return 0;
 }

 void multiplication( void )
 {
 int x, y, response, right = 0, wrong = 0;

 for ( int i = 1; i <= 10; ++i ) {
 x = rand() % 10;
 y = rand() % 10;

 cout << "How much is " << x << " times " << y << "? ";
 cin >> response;

 while ( response != x * y ) {
 ++wrong;
 incorrectMessage();
 cin >> response;
 }

 ++right;
 correctMessage();
 }

 if ( static_cast< double > ( right ) / ( right + wrong ) < .75 )
 cout << "Please ask your instructor for extra help.\n";

 cout << "That's all for now. Bye." << endl;
 }

 void correctMessage( void )
 {
 switch ( rand() % 4 ) {
 case 0:
 cout << "Very good!";
 break;
 case 1:
 cout << "Excellent!";
 break;
 case 2:
 cout << "Nice work!";
 break;
 case 3:
 cout << "Keep up the good work!";
 break;
 }

 cout << "\n\n";
 }

 void incorrectMessage( void )
 {
 switch ( rand() % 4 ) {
 case 0:
 cout << "No. Please try again.";
 break;
 case 1:
 cout << "Wrong. Try once more.";
 break;
 case 2:
 cout << "Don't give up!";
 break;
 case 3:
 cout << "No. Keep trying.";
 break;
 }

 cout << "\n? ";
 }

3.38 Write a program that plays the game of “guess the number” as follows: Your program chooses the number to be guessed by selecting an integer at random in the range 1 to 1000. The program then types: I have a number between 1 and 1000. Can you guess my number? Please type your first guess. The player then types a first guess. The program responds with one of the following: 1. Excellent! You guessed the number! Would you like to play again (y or n)? 2. Too low. Try again. 3. Too high. Try again. If the player's guess is incorrect, your program should loop until the player finally gets the number right. Your program should keep telling the player Too high or Too low to help the player “zero in” on the correct answer.

 // Exercise 3.38 Solution
 #include <iostream>

 using std::cout;
 using std::cin;

#include <cstdlib>
 #include <ctime>

 void guessGame( void );
 bool isCorrect( int, int );

 int main()
 {
 srand( time( 0 ) );
 guessGame();

 return 0;
 }

 void guessGame( void )
 {
 int answer, guess;
 char response;

 do {
 answer = 1 + rand() % 1000;
 cout << "\nI have a number between 1 and 1000.\n"
 << "Can you guess my number?\nPlease type your"
 << " first guess.\n? ";
 cin >> guess;

 while ( !isCorrect( guess, answer ) )
 cin >> guess;

 cout << "\nExcellent! You guessed the number!\n"
 << "Would you like to play again?\nPlease type (y/n)? ";
 cin >> response;

 } while ( response == 'y' );
 }

 bool isCorrect( int g, int a )
 {
 if ( g == a )
 return true;

 if ( g < a )
 cout << "Too low. Try again.\n? ";
 else
 cout << "Too high. Try again.\n? ";

 return false;
 }



3.39 Modify the program of Exercise 3.38 to count the number of guesses the player makes. If the number is 10 or fewer, print Either you know the secret or you got lucky! If the player guesses the number in 10 tries, then print Ahah! You know the secret! If the player makes more than 10 guesses, then print You should be able to do better! Why should it take no more than 10 guesses? Well, with each “good guess” the player should be able to eliminate half of the numbers. Now show why any number from 1 to 1000 can be guessed in 10 or fewer tries.

 // Exercise 3.39 Solution
 #include <iostream>

using std::cout;
 using std::cin;

#include <cstdlib>
 #include <ctime>

 void guessGame( void );
 bool isCorrect( int, int );
 void display( int );

 int main()
 {
 srand( time( 0 ) );
 guessGame();

 return 0;
 }

 void guessGame( void )
 {
 int answer, guess, total = 1;
 char response;

 do {
 answer = 1 + rand() % 1000;
 cout << "I have a number between 1 and 1000."
 << "\nCan you guess my number?\nPlease type"
 << " your first guess.\n? ";
 cin >> guess;

 while ( !isCorrect( guess, answer ) ) {
 cin >> guess;
 ++total;
 }

 cout << "\nExcellent! You guessed the number!\n";

 display( total );

 cout << "Would you like to play again?\nPlease type (y/n)? ";
 cin >> response;

 } while ( response == 'y' );
 }

 bool isCorrect( int g, int a )
 {
 if ( g == a )
 return true;

 if ( g < a )
 cout << "Too low. Try again.\n? ";
 else
 cout << "Too high. Try again.\n? ";

 return false;
 }

 void display( int t )
 {
 if ( t < 10 )
 cout << "Either you know the secret or you got lucky!\n";
 else if ( t == 10 )
 cout << "Ahah! You know the secret!\n";
 else
 cout << "You should be able to do better!\n\n";
 }
3.40 Write a recursive function power( base, exponent ) that, when invoked, returns base exponent For example, power( 3, 4 ) = 3 * 3 * 3 * 3. Assume that exponent is an integer greater than or equal to 1. Hint: The recursion step would use the relationship base exponent = base · base exponent - 1 and the terminating condition occurs when exponent is equal to 1 because base1 = base

 // Exercise 3.40 Solution
 #include <iostream>

using std::cout;
 using std::endl;
 using std::cin;

long power( long, long );

 int main()
 {
 long b, e;

 cout << "Enter a base and an exponent: ";
 cin >> b >> e;
 cout << b << " raised to the " << e << " is "
 << power( b, e ) << endl;

 return 0;
 }

 long power( long base, long exponent )
 {
 return exponent == 1 ? base : base * power( base, exponent - 1 );
 }



3.41 The Fibonacci series 0, 1, 1, 2, 3, 5, 8, 13, 21, … begins with the terms 0 and 1 and has the property that each succeeding term is the sum of the two preceding terms. a) Write a nonrecursive function fibonacci( n ) that calculates the nth Fibonacci number. b) Determine the largest Fibonacci number that can be printed on your system. Modify the program of part a) to use double instead of int to calculate and return Fibonacci numbers, and use this modified program to repeat part b).

 // Exercise 3.41 Part A Solution
 // NOTE: This exercise was accidently placed in this
 // chapter. The solution utilizes ARRAYS which are
 // introduced in the next chapter.
 #include <iostream>

using std::cout;
 using std::endl;

 int MAX = 22; // the maximum number for which the
 // fibonacci value can be calculated
 // on 2-byte integer systems

 int fibonacci( int );

 int main()
 {
 for ( int loop = 0; loop <= MAX; ++loop )
 cout << "fibonacci(" << loop << ") = " << fibonacci( loop )
 << "\n";

 cout << endl;
 return 0;
 }

 int fibonacci( int n )
 {
 int fib[ 23 ];

 fib[ 0 ] = 0;
 fib[ 1 ] = 1;

 for ( int j = 2; j <= n; ++j )
 fib[ j ] = fib[ j - 1 ] + fib[ j - 2 ];

 return fib[ n ];
}





 // Exercise 3.41 Part B Solution
 // NOTE: This exercise was accidently placed in this
 // chapter. The solution utiliizes ARRAYS which are
 // introduced in the next chapter.
 #include <iostream>

using std::cout;
 using std::endl;
 using std::ios;

 #include <iomanip>

 using std::setprecision;
 using std::setiosflags;

 double fibonacci( int );

 int main()
 {
 cout << setiosflags( ios::fixed | ios::showpoint );

 for ( int loop = 0; loop < 100; ++loop )
 cout << setprecision( 1 ) << "fibonacci(" << loop << ") = "
 << fibonacci( loop ) << endl;

 return 0;
 }

 double fibonacci( int n )
 {
 double fib[ 100 ];

 fib[ 0 ] = 0.0;
 fib[ 1 ] = 1.0;

 for ( int j = 2; j <= n; j++ )
 fib[ j ] = fib[ j - 1 ] + fib[ j - 2 ];

 return fib[ n ];
 }
3.44 (Visualizing Recursion) It is interesting to watch recursion “in action.” Modify the factorial function of Fig. 3.14 to print its local variable and recursive call parameter. For each recursive call, display the outputs on a separate line and add a level of indentation. Do your utmost to make the outputs clear, interesting and meaningful. Your goal here is to design and implement an output format that helps a person understand recursion better. You may want to add such display capabilities to the many other recursion examples and exercises throughout the text.

 // Exercise 3.44 Solution
 #include <iostream>

 using std::cout;
 using std::endl;

#include <iomanip>

 using std::setw;

 long factorial( long );
 void printRecursion( int );

 int main()
 {
 for ( int i = 0; i <= 10; ++i )
 cout << setw( 3 ) << i << "! = " << factorial( i ) << endl;

 return 0;
 }

 long factorial( long number )
 {
 if ( number <= 1 )
 return 1;
 else {
 printRecursion( number );
 return ( number * factorial( number - 1 ) );
 }
 }

 void printRecursion( int n )
 {
 cout << "number =" << setw( n ) << n << '\n';
 }
3.45 The greatest common divisor of integers x and y is the largest integer that evenly divides both x and y. Write a recursive function gcd that returns the greatest common divisor of x and y. The gcd of x and y is defined recursively as follows: If y is equal to 0, then gcd( x, y ) is x; otherwise gcd( x, y ) is gcd( y, x % y ), where % is the modulus operator.

 // Exercise 3.45 Solution
 #include <iostream>

using std::cout;
 using std::endl;
 using std::cin;

unsigned gcd( unsigned int, unsigned int );

 int main()
 {
 unsigned x, y, gcDiv;

 cout << "Enter two integers: ";
 cin >> x >> y;

 gcDiv = gcd( x, y );
 cout << "Greatest common divisor of " << x << " and "
 << y << " is " << gcDiv << endl;

 return 0;
 }

 unsigned gcd( unsigned xMatch, unsigned yMatch )
 {
 return yMatch == 0 ? xMatch : gcd( yMatch, xMatch % yMatch );
 }

Leave a Comment