Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
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.)
************************************************************************
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
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:
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
************************************************************************
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
************************************************************************
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:
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:
where arrayOut is a float array large enough to store the generated n generated points.
Example output:
************************************************************************
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:
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 . . .
float f(float x)
{
return sqrtf(x);
}
************************************************************************
( )
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:
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+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.)
************************************************************************
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 . . .
************************************************************************
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}
************************************************************************
p = x0 y0 + x1 y1 + + xn −1 yn −1 .
************************************************************************
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
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>
int main()
{
vector<int> v;
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>
int main()
{
vector<int> v;
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
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:
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:
Examples:
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:
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:
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.
c. Implement the following function for displaying the player’s and dealer’s hand:
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:
void PlayGame()
{
// Create, initialize and shuffle the deck.
CardVec deck(52);
InitDeck(deck);
ShuffleDeck(deck);
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();
int main()
{
srand((unsigned int)time(0));
}
}