Exercise Sheet 1 COMP-255 C++ Additional Exercises (Book Ch. 1, 2, 3, 4)
Exercise Sheet 1 COMP-255 C++ Additional Exercises (Book Ch. 1, 2, 3, 4)
(1) Write and run a program that plays the game of “Rock, paper, scissors”. In this game,
two players simultaneously say (or display a hand symbol representing) either “rock”,
“paper” or “scissors”. The winner is the one whose choice dominates the other. The
rules are: paper dominates (wraps) rock, rock dominates (breaks) scissors, and
scissors dominate (cut) paper. If the choices of the players are the same (for example,
both choose ‘r’), then there is a tie. (The two players/users will enter ‘r’, ‘p’ or ‘s’
representing rock, paper and scissors respectively.
Example execution:
Another example:
Please choose rock (r), paper (p) or scissors (s).
Player 1: p
Player 2: p
This is a tie!
(2) a) Write a program that will read a 4-digit integer and print out each digit of the
integer separated by two spaces.
Example run:
b) Modify the program you wrote above to work for a user-defined number of digits
(not more than 5), as follows:
Example run:
HINTS: Use switch (remember we have not yet covered loops). In this program you
may need to use the function pow(x, y) which returns xy (for example pow(2, 7)
returns 128 of type double). For this you will need to include the header file cmath by
adding the line
#include <cmath>
at the beginning of the source file. Make sure you check that the integers entered are
within the valid ranges. In case of the integers being too long, the program should
terminate with the appropriate message to the user.
(3) Write a program that reads the purchase price of an item and the cash payment amount and
prints out the change in dollars, quarters (25c), dimes (10c), nickels (5c) and pennies (1c).
Both the purchase price and the cash payment amount are entered as integer values in cents.
For example if the input is:
1249 1500
then the output would be:
Dollars: 2, Quarters: 2, Dimes: 0, Nickels: 0 and Pennies: 1
(4) Write and test a program that solves quadratic equations. A quadratic equation is an
equation of the form ax2+bx+c=0, where a, b, c are given coefficients and x is the
unknown. The coefficients are real number inputs. Since quadratic equations have two
solutions, use x1 and x2 for the solution output. The solution(s) to the quadratic
equation is given by the quadratic formula:
b b 2 4ac
x
2a
Your program should make sure that a is NOT zero (otherwise the equation is not
quadratic and you should therefore exit). If the discriminant d (b2-4ac) is negative
then the output should be “The equation has no real solutions, d<0”.
Example execution:
Another example:
Another example:
You will need to use the sqrt() function as follows to find one of the solutions:
X=(-b+sqrt(d))/(2*a);
For the sqrt() function you will need to include the header file math.h (The sqrt()
function will return a type double).