Advanced Programming Homework 9 Solution



Question 1:

Write a C++ program with the two alternate functions specified below, each of which simply triples the variable count defined in main program. Then, compare and contrast the two approaches. These two functions are:

  1. function tripleByValue that passes a copy of count by value, triples the copy and returns the new value

  1. function tripleByReference that passes count by reference via a reference parameter and triples the original value of count through its alias (i.e., the reference parameter).

Question 2:

Write a C++ program that uses a function template named min to determine the smallest of its two arguments. Test the program using integer, character, floating-point number and string arguments.

Testing function template min.

Input two integer values: 7 54

The smallest integer value is: 7

Input two characters: x e

The smallest character value is: e

Input two double values: 8.46 4.35

The smallest double value is: 4.35

Input two strings: hello world

The smallest string value is: hello


Question 3:

Write a C++ class named Person that includes four pieces of information as data members: a first name (type string), a last name (type string), an age (type int), and a salary (type int).

Your class should have a constructor that initializes the four data members. Provide a set and a get function for each data member. If the salary is non positive, set it to 0. If the age is not positive, set it to 21. Write a test program that demonstrates class Person’s capabilities. Declare two Person objects and display each object’s age and salary. Then calculate each Person’s salary for 5 years later with 10 percent increase, and display each Person’s ages and salaries for 5 years later.

Persons’ ages and salaries:

——— Lisa Roberts ———

Age: 27, Salary: $54000

——— Mark Stein ———

Age: 25, Salary: $48000

Persons’ ages and salaries for 5 years later with 10% raise:

——— Lisa Roberts ———

Age: 32, Salary: $59400

——— Mark Stein ———

Age: 30, Salary: $52800

Question 4:

Implement a C++ class TicTacToe that would enable you to write a program to play the game of tictac-toe with the following features:

  • The class contains as private data a 3-by-3 two-dimensional array of integers.

  • The constructor should initialize the empty board to all zeros.

  • Design your program to allow two human players.

  • Use a text-based interface for your tic-tac-toe application.

  • Wherever the first player moves, place a 1 in the specified square; place a 2 wherever the second player moves.

  • Each move must be to an empty square.

  • After each move, determine if the game has been won or if the game is a draw.

A sample user interface is given next.