Sei sulla pagina 1di 14

C++ Module I Extra Exercises Part 1: Chapters 1-4

C++ Module I Extra Exercises Part 1: Chapters 1-4

The following exercises can be programmed using only techniques from Chapters 1-4. It
is up to you to figure out which tools to use to solve the problem. They vary in difficulty
and are in no particular order (e.g., they do not necessarily start easy and get harder).
Let me know if you find errors or typos.

************************************************************************

1. Write a program that inputs two points ( x1 , y1 ) , ( x2 , y2 ) and outputs the midpoint.
 x + x y + y2 
The midpoint is given by the formula: ( mx , my ) =  1 2 , 1 .
 2 2 

************************************************************************

2. Write a function IsOdd that determines if an integer is odd. Write a function IsEven
that determines of an integer is even. Then write a driver program to test your functions.
(Hint: Use the % operator.)

************************************************************************

3. A floating-point number x can be rounded to k decimal places as follows:

rd ( x ) =
(
floor x ⋅10k + 0.5 ).
k
10

For example, if we round 3.14159 to two decimal places then we would expect to get
3.14; using the above formula, we obtain that:

rd ( 3.14159 ) =
(
floor 3.14159 ⋅102 + 0.5 )
2
10
floor ( 314.159 + 0.5 )
=
102
floor ( 314.659 )
=
102
314
=
102
= 3.14

As another example, let us round 6.283185 to the fourth decimal place:

Frank Luna Page 1 www.gameinstitute.com


C++ Module I Extra Exercises Part 1: Chapters 1-4

rd ( 6.283185 ) =
(
floor 6.283185 ⋅104 + 0.5 )
4
10
floor ( 62831.85 + 0.5 )
=
104
floor ( 62832.35 )
=
104
62832
=
104
= 6.2832

Write a function that rounds a double x to the kth decimal place, where k is a specified
parameter; that is, the function prototype looks like this:

double Round(double x, int k);

The function should return the rounded value. Write a driver program to test your
function.

************************************************************************

4. Write a program that inputs an integer n ≥ 1 . Then compute and output the sum of the
integers from 1 to n. That is, compute and output the sum
n

∑ j = 1+ 2 + 3 +
j =1
+ n − 2 + n − 1 + n . For example, for n = 4 the output would be 10

because 1 + 2 + 3 + 4 = 10.

************************************************************************

5. Write a program that inputs an integer n ≥ 1 . Then compute and output the alternating
n

∑ ( −1) + ( −1)
j −1 n −1
sum j 2 = 1 − 4 + 9 − 16 + n 2 . For example, for n = 4 the output
j =1

would be –10 because 1 – 4 + 9 – 16 = –10.

************************************************************************

6. Write a program that inputs an integer n ≥ 2 . Then output the sequence of size n with
a bit pattern where the elements alternate between 0 and 1. For example, for n = 9 the
output would be:

0 1 0 1 0 1 0 1 0

************************************************************************

Frank Luna Page 2 www.gameinstitute.com


C++ Module I Extra Exercises Part 1: Chapters 1-4

7. Write a program that inputs an integer n ≥ 2 . Then output the n × n matrix with a bit
pattern where the elements alternate between 0 and 1. For example, for n = 6 the output
would be:

0 1 0 1 0 1
1 0 1 0 1 0
0 1 0 1 0 1
1 0 1 0 1 0
0 1 0 1 0 1
1 0 1 0 1 0

************************************************************************

8. Write a program that inputs an integer n ≥ 2 , and integer D . Then output the n × n
matrix with the following pattern:

D 0 0
0 D 
 .
 0
 
0 0 D

That is, the matrix consists of all zeros except along the main diagonal; the integer D is
placed along the main diagonal.

************************************************************************

9. Write a program that inputs an integer n ≥ 2 , and integers D , and U . Then output the
n × n matrix with the following pattern:

D U U
0 D 
 .
 U
 
0 0 D

That is, the integer D is placed along the main diagonal. The integer U is placed in
every element that lies above the main diagonal. And the integer 0 is placed in every
element that lies below the main diagonal.

************************************************************************

10. Write a program that inputs an integer n ≥ 2 , and integers D , U , and L . Then
output the n × n matrix with the following pattern:

Frank Luna Page 3 www.gameinstitute.com


C++ Module I Extra Exercises Part 1: Chapters 1-4

D U U
L D 
 .
 U
 
L L D

That is, the integer D is placed along the main diagonal. The integer U is placed in
every element that lies above the main diagonal. And the integer L is placed in every
element that lies below the main diagonal.

************************************************************************

11. Write a program to compute π 47 without using the pow or powf functions.

************************************************************************

12. Write a function called LineSpace that generates n evenly spaced nodal points from
a to b . The function prototype should be:

void LineSpace(float a, float b, int n, float arrayOut[]);

where arrayOut is a float array large enough to store the generated n generated points.
Example output:

Enter an interval [a,b] and number of nodal points n.


Input a = 1
Input b = 2
Input n = 11
1 1.1 1.2 1.3 1.4 1.5 1.6 1.7 1.8 1.9 2
Press any key to continue . . .

Enter an interval [a,b] and number of nodal points n.


Input a = -1.5
Input b = 0.5
Input n = 9
-1.5 -1.25 -1 -0.75 -0.5 -0.25 0 0.25 0.5
Press any key to continue . . .

************************************************************************

13. Write a function called FuncEval (function evaluation) that takes a pointer to a real-
valued function f and an array of n distinct nodal points ( x0 , x1 , … , xn −1 ) , where xi > x j
for i > j . (By “real-valued” function, we mean a function that inputs a real number and
outputs a real number.) The function is to return the array ( f ( x0 ) , f ( x1 ) , … , f ( xn −1 ) ) ;
that is, the function evaluated at each nodal point. The function FuncEval should have
the following prototype:

Frank Luna Page 4 www.gameinstitute.com


C++ Module I Extra Exercises Part 1: Chapters 1-4

void FuncEval(float (*f)(float), float arrayIn[],


float arrayOut[], int n);

Here is an example output:

x_i points:
0 0.4 0.8 1.2 1.6 2 2.4 2.8 3.2 3.6 4

f(x_i) points:
0 0.632456 0.894427 1.09545 1.26491 1.41421 1.54919 1.67332 1.78885 1.89737 2
Press any key to continue . . .

The above example uses 11 points and the following f:

float f(float x)
{
return sqrtf(x);
}

************************************************************************

14. Trapezoidal Rule: Consider a continuous function f defined on the interval [ c, d ] .


The area under the curve can be approximated using a trapezoidal rule; see Figure 1.
That is,

1. Divide the segment [ c, d ] into n evenly spaced intervals  x j −1 , x j  for


j = 1, 2,… , n , each containing a trapezoid. (Note that for n subintervals there are
n + 1 grid points.)
2. Sum the area of all the trapezoids to approximate the area under the curve. (We
can compute the area of a trapezoid easily using the formula A = 12 ( a + b ) h ; see
Figure 2.)

Summing the area of all the trapezoids gives the formula:

( )
n
A = ∑ 12 h f ( x j −1 ) + f ( x j )
j =1

( )
n
= 12 h∑ f ( x j −1 ) + f ( x j )
j =1

= 12 h ( f ( x0 ) + f ( x1 ) ) + ( f ( x1 ) + f ( x2 ) ) + + ( f ( xn − 2 ) + f ( xn −1 ) ) + ( f ( xn −1 ) + f ( xn ) ) 
= 12 h  f ( x0 ) + 2 f ( x1 ) + 2 f ( x2 ) + + 2 f ( xn −1 ) + f ( xn ) 
h n −1 
=  f ( x0 ) + 2 ∑ f ( x j ) + f ( xn ) 
2 j =1 

For those not comfortable with this math, the formula you need to program is:

Frank Luna Page 5 www.gameinstitute.com


C++ Module I Extra Exercises Part 1: Chapters 1-4

h n −1 
A=  ( 0 ) ∑ f ( x j ) + f ( xn )  .
f x + 2
2 j =1 

This formula gives the approximate area under the curve, and is called the trapezoidal
rule.
Intuitively, it should be obvious that if we make the subintervals smaller (thereby
adding more subintervals), we should get a better approximation. Write a program to
approximate the area under the curve e x on the interval [0, 2] using step sizes h = 0.2 ,
h = 0.1 , h = 0.05 and h = 0.025 . Note that the exact area is e 2 − 1 . How good are your
approximations? Do they get better as you decrease h ? How much better?

Figure 1: We divide the interval [0.2, 2.0] into subintervals of length h = 0.2 . For each subinterval
 x j −1 , x j  , we construct a trapezoid with height h and lengths f ( x j −1 ) and f ( x j ) . We can then
approximate the area under the curve as the sum of the trapezoid areas. Observe how the
trapezoids do not agree with the given curve exactly; hence this method is only an approximation.

Remark: The area of a trapezoid can be derived as follows (see Figure 2). Let
b = bL + bM + bR ; and note that a = bM . The area of the trapezoid is:

A = ( Area of Middle Rectangle ) × ( Area of Left Triangle ) × ( Area of Right Triangle )


= bM h + 12 bL h + 12 bR h
= h ( bM + 12 bL + 12 bR )
= h ( 2bM + bL + bR ) 12
= h ( bM + bM + bL + bR ) 12
= h ( bM + ( bL + bM + bR ) ) 12
= h ( a + b ) 12

Frank Luna Page 6 www.gameinstitute.com


C++ Module I Extra Exercises Part 1: Chapters 1-4

Figure 2: Finding the area of a trapezoid.

************************************************************************

15. Bisection Method: Consider a continuous function f on an interval [ a, b ] such that


f ( a ) and f ( b ) have opposite signs. We wish to find the value x ∈ [ a, b ] such that
f ( x ) = 0 ; see Figure 3. The algorithm is as follows:

 a+b 
1. Set m =  
 2 
2. IF f ( m ) == 0 OR ( b − a ) 2 < ε
a. x = m
b. STOP
3. IF f ( a ) ⋅ f ( m ) > 0
a. a′ = m
b. b′ = b
4. ELSE
a. a′ = a
b. b′ = m
5. Repeat the process to the interval [ a′, b′]

As you can see, the algorithm is reminiscent of binary search, because in each step, we
eliminate half of our search candidates. Note that ε is a small tolerance number you
specify close to zero, which determines how good of an approximation you want.
Numerically, we consider numbers less than ε to be zero (e.g., you might try ε = 10−5 ).
Thus the line ( b − a ) 2 < ε asks if half the length of the current interval is close to zero.
If it is, then the current m must be close to the solution x , and so we stop because we
have an acceptable approximation. For this exercise, implement the bisection method to
find x ∈ [ 0, 2] such that f ( x ) = x 2 − 2 = 0 ; note that this gives a numerical
approximation for 2 . (Tip: In order to get comfortable for what the above algorithm is
doing at each step, the student should do a few iterations of the algorithm by hand, for the
problem of finding the root of f ( x ) = x 2 − 2 = 0 ; at each step, record the current interval
[ a, b] , so that you can see how it changes over each iteration of the algorithm.)

Frank Luna Page 7 www.gameinstitute.com


C++ Module I Extra Exercises Part 1: Chapters 1-4

Figure 3: Bisection method.

************************************************************************

16. Write a program that generates a random number from 0 to 99. Ask the user to guess
the number generated. If the user guesses correct, display a congratulations; if not, let the
user know if they guessed too high or too low, and let them guess again. Keep letting the
user guess until they guess correctly, or quit.

************************************************************************

17. Write a function FindMax that inputs an array of floats and returns the maximum
value in the array. Similarly, write a function FindMin that inputs an array of floats
and returns the minimum value in the array. Here is an example output:

data = {1, 5.32, 0.25, 11.33, -4, 13, 21, -3, 0.1, 9}
Max = 21
Min = -4
Press any key to continue . . .

************************************************************************

18. Let ( s0 , s1 , … sm −1 ) and ( t0 , t1 , … tn −1 ) be two int arrays of size m and n elements,


respectively. Write a function Merge that merges these two arrays to produce a third
array, ( s0 , s1 , … sm −1 , t0 , t1 , … tn −1 ) , of size m + n. The prototype of Merge is as follows:

void Merge(int s[], int t[], int out[], int m, int n);

Note that the output array, out, needs to be large enough to store the result (i.e., the
merged array). Here is an example output, where we merge s and t into r:

s = {1, 2, 3, 4, 5, 6}
t = {7, 8, 9, 0}
r = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0}

Frank Luna Page 8 www.gameinstitute.com


C++ Module I Extra Exercises Part 1: Chapters 1-4

Press any key to continue . . .

************************************************************************

19. Let ( x0 , x1 , … xn −1 ) and ( y0 , y1 , … yn −1 ) be float arrays (i.e., they represent a finite


sequence of real numbers). The inner product is defined by:

p = x0 y0 + x1 y1 + + xn −1 yn −1 .

For example, the inner product of (1, 2, 3) and (1, 2, 13 ) is p = 1⋅1 + 2 ⋅ 2 + 3 ⋅ 13 = 6 .


Write a function to compute the inner product of two n-dimensional float arrays; the
prototype should be as follows:

float InnerProduct(float x[], float y[], int n);

************************************************************************

20. Write a program that inputs two strings, s0 s1 … sm −1 and t0t1 … tm −1 , both of size m,
where each sk and tk is a character (for k = 0, 1, … , m − 1 ). Generate a third string by
shuffling the given two to get s1t1s2t1 … smtm . For example, if the first string is abcd and
the second string xyzw then the shuffled string would be axbyczdw.

************************************************************************

21. Write a program that inputs a string S. Next, ask the user to input a character C in S,
then have the program count and output the total number of times the character C appears
in S. For example, the character ‘m’ appears three times in the string “game
programming.” If the user inputs a character that is not in S, then the count is zero.

************************************************************************

22. Write a program that inputs a string S that contains at least two words (take a word as
a sequence of characters with no space between the characters). Write a program that
extracts every other word and stores the result in a string T; also output T. For example,
let S = “The C++ Programming Language by Bjarne Stroustrup” then choosing the odd
words we have that T = “C++ Language Bjarne”.

************************************************************************

23.

Background Info: We learned in Chapter 4 that std::vector can be used as a resizable array, using
the resize method. In addition, there are some other convenient methods, which may be helpful for the
following exercise. First, instead of using resize to explicitly specify the size we want, we can you the

Frank Luna Page 9 www.gameinstitute.com


C++ Module I Extra Exercises Part 1: Chapters 1-4

push_back method, which adds a new element to the end of the vector; the following simple code
illustrates.

#include <iostream>
#include <string>
#include <vector>

using namespace std;

int main()
{
vector<int> v;
cout << "v.size() = " << v.size() << endl;

for(int i = 0; i < 5; ++i)


{
v.push_back(i*i);
cout << "v.size() = " << v.size() << endl;
}
}

Output:

v.size() = 0
v.size() = 1
v.size() = 2
v.size() = 3
v.size() = 4
v.size() = 5
Press any key to continue . . .

As you can see, using this method, the size automatically grows as we add elements, and we never have to
worry about resizing the vector ourselves (the vector internally keeps track of when it needs to resize
itself). This next example code illustrates the back and pop_back methods. The back method returns a
reference to the last element added to the vector (i.e., a reference to the element with index vec.size()-
1). The pop_back method removes the last element from the vector (and thus decreases the size of the
vector by one).

#include <iostream>
#include <string>
#include <vector>

using namespace std;

int main()
{
vector<int> v;

for(int i = 0; i < 5; ++i)


v.push_back(i*i);

for(int i = 0; i < 5; ++i)


{
cout << "v.back() = " << v.back() << "\t";
cout << "v.size() = " << v.size() << endl;
v.pop_back();
}
}

Output:

v.back() = 16 v.size() = 5
v.back() = 9 v.size() = 4
v.back() = 4 v.size() = 3
v.back() = 1 v.size() = 2
v.back() = 0 v.size() = 1

Frank Luna Page 10 www.gameinstitute.com


C++ Module I Extra Exercises Part 1: Chapters 1-4

Press any key to continue . . .

Simple Blackjack: The following exercise will walk you through making a “simple”
blackjack game; the game is simplified by removing options like bets, splits, double
downs, and insurance, and only two players are supported (the human user and the
computer dealer); the reader may wish to implement these features at their leisure. (If
you do not know the rules for blackjack, they are easily obtained online via a web
search.) First, some background information on the data representation is presented.
We represent a deck of 52 cards by an array of 52 integers that take values from 0
to 51:

typedef std::vector<int> CardVec;


const int NUM_CARDS = 52;

void InitDeck(CardVec& deck)


{
for(int i = 0; i < NUM_CARDS; ++i)
deck[i] = i;
}

// Create and initialize the deck...


CardVec deck(52);
InitDeck(deck);

An integer from 0-51 is not very descriptive of what the actual card is (e.g., is it a queen
of diamonds?), so we create the following map:

const std::string CardNames[52] =


{
"H2", "H3", "H4", "H5", "H6", "H7", "H8", "H9", "H10", "HJ", "HQ", "HK", "HA",
"D2", "D3", "D4", "D5", "D6", "D7", "D8", "D9", "D10", "DJ", "DQ", "DK", "DA",
"S2", "S3", "S4", "S5", "S6", "S7", "S8", "S9", "S10", "SJ", "SQ", "SK", "SA",
"C2", "C3", "C4", "C5", "C6", "C7", "C8", "C9", "C10", "CJ", "CQ", "CK", "CA"
};

Examples:

CardNames[ deck[0] ] == “H2” (i.e., 2 of hearts)


CardNames[ deck[11] ] == “HK” (i.e., king of hearts)
CardNames[ deck[18] ] == “D7” (i.e., 7 of diamonds)
CardNames[ deck[34] ] == “S10” (i.e., 10 of spades)
CardNames[ deck[51] ] == “CA” (i.e., ace of clubs)

In this way, given an integer from 0-51, we can easily obtain a description of the card it
represents.
In addition, each card has a point value (e.g., a royal card is with 10 points in
blackjack). We use the following map to associate a point value with a card:

const int CardValues[52] =


{
2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 11,
2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 11,
2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 11,

Frank Luna Page 11 www.gameinstitute.com


C++ Module I Extra Exercises Part 1: Chapters 1-4

2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 11


};

Here we give aces a value of 11, however, an ace can also have a value of 1 to prevent a
bust; so in the code, you will need to count how many aces the player/dealer has, and
count them as 1, as needed, if the player/dealer would otherwise bust.

a. A deck of cards can be shuffled in the following way: for each card in the deck,
swap it with some other random card in the deck (you can swap a card with
itself). Implement the following function to shuffle the deck:

void ShuffleDeck(CardVec& deck);

b. Implement the following function, which sums the card values of the given hand.
For example, a hand of “H9”, “SA”, and “CK” would sum to 20. Remember to
count aces as 1-point value, as needed, in order to prevent a bust. The function
takes a vector of cards representing the hand, and returns the total value of the
hand.

int SumCardValues(const CardVec& cards);

c. Implement the following function for displaying the player’s and dealer’s hand:

void PrintCards(const CardVec& cards, bool dealer);

The first parameter is a vector of cards representing the hand; the second
parameter should be true if outputting the dealer’s cards and false if outputting the
player’s cards (this way you can print “You have” or “Dealer has” depending on
whose hand you are printing). Here is an example output:

You have: DA, D3, D4


Dealer has: S5, C5, H6

d. Complete the following function by filling in the “TODO” sections:

void PlayGame()
{
// Create, initialize and shuffle the deck.
CardVec deck(52);
InitDeck(deck);
ShuffleDeck(deck);

// Create a vector of cards for each player, representing the


// hand of the player.
CardVec playerCards;
CardVec dealerCards;

// Deal out two initial cards to each player and display


// initial hands.
playerCards.push_back( deck.back() );
deck.pop_back();

Frank Luna Page 12 www.gameinstitute.com


C++ Module I Extra Exercises Part 1: Chapters 1-4

playerCards.push_back( deck.back() );
deck.pop_back();

PrintCards(playerCards, false);

dealerCards.push_back( deck.back() );
deck.pop_back();

PrintCards(dealerCards, true);

dealerCards.push_back( deck.back() );
deck.pop_back();

// TODO: Loop until player busts or stands.


while(1)
{
// Ask user to hit or stand. If hit, give player a new
// card from the deck. Check for bust—if player busts,
// then player loses.
}

// TODO: Loop until dealer busts or stands.


while(1)
{
// Dealer stands if he/she has at least 18 points and
// hits otherwise. Check for bust—if dealer busts,
// then dealer loses.
}

// TODO: No one busted, who has the highest hand,


// or is it a push? Output who won.
}

e. Test your function implementations with the following driver:

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

bool quit = false;


while(!quit)
{
std::string choice;
std::cout << "(1) Play game or (2) Quit? ";
std::cin >> choice;

if( choice == "1" )


PlayGame();
else if( choice == "2" )
quit = true;
else
std::cout << "Invalid input, try again."
<< std::endl;

Frank Luna Page 13 www.gameinstitute.com


C++ Module I Extra Exercises Part 1: Chapters 1-4

}
}

Here is an example output for two games:

(1) Play game or (2) Quit? 1


You have: C8, D10
Dealer has: S5
(1) Hit or (2) Stand? 2
You stand.
Dealer hits, Dealer has: S5, C5, H6
Dealer hits, Dealer has: S5, C5, H6, HQ
Dealer Busted! You Win!

(1) Play game or (2) Quit? 1


You have: DA, D3
Dealer has: DQ
(1) Hit or (2) Stand? 1
You hit, you have: DA, D3, D4
(1) Hit or (2) Stand? 1
You hit, you have: DA, D3, D4, HJ
(1) Hit or (2) Stand? 2
You stand.
Dealer hits, Dealer has: DQ, D2, H8
Dealer Stands.
You lost!

Frank Luna Page 14 www.gameinstitute.com

Potrebbero piacerti anche