Solutions to Exercises in Study Guide
Solutions to Exercises in Study Guide
LESSON 1
Exercise 1.1
Descriptive Comment:
StatementSequence:
cout << "Hello world"; return 0;
Exercise 1.2
//A poem
#include <iostream>
using namespace std;
int main( )
{
cout << "Twinkle, twinkle, little bat!" << endl;
cout << "How I wonder what you're at?" << endl;
cout << "Up above the world you fly," << endl;
cout << "Like a tea-tray in the sky." << endl;
return 0;
}
LESSON 2
Exercise 2.1
| |
16 + 11
|
27
-9 - -3
|
-6
Open Rubric
(iii) (((6 * 7) / 8) * 9)
42 / 8 * 9
|
5 * 9
|
45
| |
-1 + 0 * 5
|
-1 + 0
|
-1
-1 + -5 + 56
-6 + 56
|
50
Exercise 2.2
Exercise 2.3
int main( )
{
2
cout << "The remainder of 234 divided by 13 is ";
cout << 234 - (234 / 13) * 13 << endl;
return 0;
}
The round brackets are not necessary but their use makes the program more readable.
LESSON 3
Exercise 3.1
int main( )
{
int i, j, k;
cout << "Enter three numbers: ";
cin >> i >> j >> k;
cout << "In reverse: " << k << " " << j << " " << i << endl;
return 0;
}
Exercise 3.2
2 6 4
x + y / z is 3
x % z is 2
y * z / x + 2 is 14
5 1 3
x + y / z is 5
x % z is 2
y * z / x + 2 is 2
If 5 1 3 are entered: y * (z / x + 2) is 2
Exercise 3.3
int main( )
{
int fahrenheit;
cout << "Enter the temperature in Fahrenheit: ";
cin >> fahrenheit;
cout << "Celsius = " << 5 *(fahrenheit - 32) / 9 << endl;
return 0;
}
LESSON 4
Exercise 4.1
int main( )
{
int fahrenheit, celsius;
cout << "Enter the temperature in Fahrenheit: ";
cin >> fahrenheit;
celsius = 5 * (fahrenheit - 32) / 9;
cout << "Celsius = " << celsius << endl;
return 0;
}
Exercise 4.2
int main( )
{
int items, itemsPerBox, boxes, remainder;
cout << "How many items to be packed? ";
cin >> items;
cout << "How many items fit in a box? ";
cin >> itemsPerBox;
boxes = items / itemsPerBox;
remainder = items % itemsPerBox;
cout << "You will need " << boxes << " boxes." << endl;
cout << "There will be " << remainder << " items left over." << endl;
return 0;
}
Exercise 4.3
int n = 10; // 10
n += 3; // 13
n /= 2; // 6
n++; // 7
n %= 4; // 3
n -= 5; // -2
LESSON 5
Exercise 5.1
j k m n
Line 7: ? ? ? ?
j k m n
Line 8: 3 ? ? ?
14
j k m n
Line 9: 3 2 ? ?
j k m n
Line 10: 3 2 1 ?
j k m n
Line 11: 3 2 1 6
j k m n
Line 12: 3 2 1 6
j k m n
Line 13: 9 2 1 6
j k m n
Line 14: 9 3 1 6
j k m n
Line 15: 9 3 1 6
3 2 1 6
9 3 1 6
Exercise 5.2
1 //Think of a number
2 #include <iostream>
3 using namespace std;
4
5 int main( )
6 {
7 const int NUMBER = 40;
8 int answer;
9 cout << "Think of a number between 30 and 50. Write it down" << endl;
10 cout << "Then do the following calculations on paper:" << endl << endl;
11 cin.get( );
12 cout << "Double it" << endl;
13 cin.get( );
14 answer = NUMBER * 2;
15 cout << "Add 29 to this" << endl;
16 cin.get( );
17 answer += 29;
18 cout << "Double the result again" << endl;
19 cin.get( );
20 answer *= 2;
21 cout << "Subtract the original number from your answer" << endl;
22 cin.get( );
23 answer -= NUMBER;
24 cout << "Divide the answer by your original number and throw away any remainder"
<< endl;
25 cin.get( );
26 answer /= NUMBER;
27 cout << "Your final answer is " << answer << endl;
28 return 0;
29 }
5
NUMBER answer
Line 7: 40 ?
NUMBER answer
Line 14: 40 80
NUMBER Answer
NUMBER Answer
NUMBER answer
NUMBER answer
Line 26: 40 4
LESSON 6
Exercise 6.1
int main( )
{
float length, width, area;
return 0;
}
Exercise 6.2
int main( )
6
{
const float PRICE_PER_METRE = 59.50;
float length, width, area, price;
//Fixed-point notation
cout.setf(ios::fixed);
return 0;
}
Exercise 6.3
(i) Implicit conversions take place in line 13 (when the integer quotient of the integers w and x is assigned
to the floating point variable y), line 14 (when the value of the floating point variable y is subtracted
from the integer value of w), and twice in line 16 (when firstly the quotient of the floating point variable y
and the integer x is found and secondly when the integer value of the right-hand side of the
assignment statement is stored in the floating point variable answer).
(ii) The value of result will be 11, and the value of answer will be 3.
Exercise 6.4
14 1.123 65
73.46 27.2727
7
LESSON 7
Exercise 7.1
(i) x + y is 579
(ii) x + y is 123456
(iii) x + y is c
In part (iii), the character '1' is stored in x and the character '2' is stored in y. In the statement z = x + y, these
character values are implicitly converted to the numerical values 49 and 50 (the ASCII codes of '1' and '2',
respectively) and then added to give 99. This number is then implicitly converted to the character with ASCII code
99, namely the character 'c'.
Exercise 7.2
int main( )
{
char letter;
int position;
cout << "Enter an upper case letter: ";
cin >> letter;
position = letter - 'A' + 1;
cout << letter << " is in position " << position
<< " in the alphabet" << endl;
return 0;
}
Exercise 7.3
//Performs a spoonerism
#include <string>
#include <iostream>
using namespace std;
int main( )
{
string word1, word2, spoonerism;
char letter1, letter2;
return 0;
}
Exercise 7.4
//Dialogue generator
#include <iostream>
#include <string>
using namespace std;
int main( )
{
string name1, name2, colour, noun, adjective;
8
int number;
return 0;
}
Exercise 7.5
With the knowledge that you have acquired up to now, it is impossible to do this exercise as it was stated. It is
essential to use a loop, but loops have not been discussed yet. (However, if one knows beforehand that 10000 will
be entered when the program prompts one to enter a number, one may include 10000 cout statements in the
program!)
//Computer punishment
#include <iostream>
#include <string>
using namespace std;
int main( )
{
int n;
string s;
cout << "Computer punishment" << endl;
cout << "-------------------" << endl;
cout << "Repetitions? ";
cin >> n;
cin.get( ); //necessary between cin >> and getline
cout << "Message? ";
getline(cin, s, '\n');
return 0;
}
9
LESSON 8
Exercise 8.1
Exercise 8.2
Exercise 8.3
if (balance >= 0)
cout << "Credit" << endl;
else
cout << "Debit" << endl;
Exercise 8.4
if (x == y)
cout << "x is equal to y" << endl;
else
cout << "x is not equal to y" << endl;
Exercise 8.5
Exercise 8.6
int main( )
10
{
float lenth, width, areaFloor, areaNotCovered;
const float CARPET_SIZE = 100;
return 0;
}
LESSON 9
Exercise 9.1
0 times. If the condition of the while loop is False the very first time the loop is entered, the body of the loop will be
skipped.
Exercise 9.2
There are two problems. Firstly, the loop control variable count is not changed inside the body of the loop. Its value
stays equal to 0 and so the condition (assuming that num is greater than 0) never becomes False. This means that
we have an infinite loop. We have to insert the statement
count++;
Secondly, if a value less than or equal to 0 is entered for num, the body of the while loop will never be executed,
and thus no value will be assigned to last. We can correct this by replacing the final cout statement with:
if (num > 0)
cout << "The last value entered was " << last << endl;
else
cout << "Error: the number of items cannot be zero or less." << endl;
So we should have:
total = 0.0;
cout << "Enter number of values: ";
cin >> num;
count = 0;
while (count < num)
{
cout << "Enter a value : ";
cin >> value;
last = value;
count++;
}
if (num > 0)
cout << "The last value entered was " << last << endl;
11
else
cout << "Error: the number of items cannot be zero or less." << endl;
If the idea was to add all the numbers, we would also have to insert the statement
total += value;
into the body of the loop after value has been input.
Exercise 9.3
//Sipho's money
#include <iostream>
using namespace std;
int main( )
{
const float INTEREST = 0.045;
const float START_AMOUNT = 1000.00;
const float SAVE_AMOUNT = 500.00;
const int NUM_YEARS = 18;
float balance;
int year;
return 0;
}
Exercise 9.4
int main( )
{
const int MAX_MASS = 10000;
int mass, totalMass;
totalMass = 0;
cout << "Please enter mass of first piece of luggage (0 to stop): ";
cin >> mass;
while (mass != 0)
{
totalMass += mass;
cout << "Please enter mass of next piece of luggage (0 to stop): ";
cin >> mass;
}
12
else
cout << totalMass << "kg is fine." << endl;
return 0;
}
LESSON 11
Exercise 11.1
//Water consumption
#include <iostream>
using namespace std;
int main( )
{
const float RATE_0 = 10;
const float RATE_1 = RATE_0 * 1.5; // this is permissible
const float RATE_2 = RATE_0 * 2.0; // this is permissible
float units, amount;
return 0;
}
Exercise 11.2
//Playschool criteria
#include <iostream>
#include <string>
using namespace std;
int main( )
{
int ageChild, income, ageParent;
char status;
bool crit1, crit2, crit3, crit4;
13
crit2 = (status == 'Y') || (status == 'y');
crit3 = income < 60000;
crit4 = ageParent <= 30;
return 0;
}
Exercise 11.3
Exercise 11.4
int main( )
{
const int SECRET = 23; // or any other value between 1 and 100
int guess, numberOfTries;
bool found;
found = false;
numberOfTries = 0;
if (found)
cout << "Well done! You got the number in "
<< numberOfTries << " guesses." << endl;
else
cout << "Tough luck! Your 10 guesses are over." << endl;
return 0;
}
LESSON 12
Exercise 12.1
int main ( )
14
{
int a, b, c;
if ((a + b) == c)
cout << "Yes, a + b = c";
else if ((a + c) == b)
cout << "Yes, a + c = b";
else if ((b + c) == a)
cout << "Yes, b + c = a";
else
cout << "No, one number is not equal to the sum of the other two.";
cout << endl;
return 0;
}
Exercise 12.2
int main( )
{
int throw1, throw2, sum;
return 0;
}
Exercise 12.3
int main( )
{
int year;
bool leap;
leap = false;
cout << "Please enter year: ";
cin >> year;
if ((year % 100) == 0)
{
15
if ((year % 400) == 0)
leap = true;
}
else
if ((year % 4) == 0)
leap = true;
if (leap)
cout << year << " is a leap year." << endl;
else
cout << year << " is not a leap year." << endl;
return 0;
}
Exercise 12.4
//Cereal discount
#include <iostream>
using namespace std;
int main( )
{
float amount, discountPerc, finalAmount;
return 0;
}
LESSON 13
Exercise 13.1
//Choices of university
#include <iostream>
using namespace std;
int main( )
{
float mark, earn;
char category;
cout << "What was her average mark? ";
cin >> mark;
// find category of mark
if (mark >= 90)
category = 'A';
16
else if (mark >= 75)
category = 'B';
else if (mark >= 60)
category = 'C';
else
category = 'D';
switch (category)
{
case 'A':
cout << "She may go to any university"
<< " and she will get a car." << endl;
break;
case 'B':
if (earn > 5000)
cout << "She may go to any university"
<< " and she will get a car." << endl;
else
cout << "She may go to any university"
<< " but she will not get a car." << endl;
break;
case 'C':
cout << "She has to study at the nearest university." << endl;
break;
case 'D':
cout << "She cannot go to university." << endl;
}
return 0;
}
Exercise 13.2
int main( )
{
int throw1, throw2, sum;
cout << "Enter 2 numbers representing the throws of a pair of dice: ";
cin >> throw1 >> throw2;
sum = throw1 + throw2;
switch (sum)
{
case 7:
case 11:
cout << "You win!";
break;
case 2:
cout << "Snake eyes!";
break;
case 12:
cout << "Good shot!";
break;
default:
cout << "Try again.";
}
cout << endl;
17
return 0;
}
Exercise 13.3
// Parkade payment
#include <iostream>
using namespace std;
int main( )
{
char typeOfVehicle;
int hours, due;
switch (hours)
{
case 1:
due = 2;
break;
case 2:
due = 3;
break;
case 3: case 4:
case 5:
due = 5;
break;
default:
due = 10;
}
if ((typeOfVehicle == 'T') || (typeOfVehicle == 't'))
due += 1;
cout << "You owe R" << due << endl;
return 0;
}
Exercise 13.4
int main( )
{
int month, year, numberOfDays;
bool leap;
cout << "Which month (1-12) are you interested in? ";
cin >> month;
cout << "Which year? ";
cin >> year;
switch (month)
{
case 1:
case 3:
case 5:
case 7:
case 8:
18
case 10:
case 12:
numberOfDays = 31;
break;
case 4:
case 6:
case 9:
case 11:
numberOfDays = 30;
break;
case 2:
leap = ( ((year % 4) == 0) && !((year % 100) == 0) )||
((year % 400) == 0);
if (leap)
numberOfDays = 29;
else
numberOfDays = 28;
break;
default:
cout << "Error. Month has to be between 1 and 12." << endl;
numberOfDays = 0;
}
cout << "The " << month << "th month of " << year
<< " has " << numberOfDays << " days." << endl;
return 0;
}
LESSON 14
Exercise 14.1
int main( )
{
int numPeople, j;
float oneHeight, totHeight, aveHeight;
if (numPeople > 0)
{
totHeight = 0;
j = 1;
while (j <= numPeople)
{
cout << "Enter height in metre: ";
cin >> oneHeight;
totHeight += oneHeight;
j++;
}
aveHeight = totHeight / numPeople;
cout.setf(ios::fixed);
cout.precision(2);
cout << "Average height is " << aveHeight << "m" << endl;
}
else
cout << "No people in the survey." << endl;
19
return 0;
}
Exercise 14.2
//Maintains a cheque account
#include <iostream>
using namespace std;
int main( )
{
float balance, transac;
cout.setf(ios::fixed);
cout.precision(2);
while (transac != 0)
{
cout << "Now the balance of the account is R" << balance << endl;
cin >> transac;
balance += transac;
}
return 0;
}
Exercise 14.3
int main( )
{
int num = 10;
return 0;
}
Exercise 14.4
int main( )
{
const float COMPARE_SALARY = 100000;
float salary, percentageAbove;
char more;
int numTotal = 0;
int numAbove = 0;
do
{
cout << "Please enter salary: ";
cin >> salary;
numTotal ++;
if (salary > COMPARE_SALARY)
numAbove++;
cout << "Are there more salaries to be input (Y or N)? ";
cin >> more;
} while ((more == 'Y') || (more == 'y'));
cout.setf(ios::fixed);
cout.precision(2);
percentageAbove = numAbove * 100.0 / numTotal;
cout << endl << percentageAbove << "% of the salaries are above R"
<< COMPARE_SALARY << endl;
return 0;
}
Exercise 14.5
The value of i is 5
The first declaration of i (namely int i = 23;) is overridden by the second declaration (inside the main
function). This (second) declaration is valid throughout the main function, except if another variable with the same
name were to be declared inside a block nested in the main function. This is what happens with the third
declaration of variable i. It is done inside the while loop. All references inside the body of the loop refer to that
specific i. Once the loop is exited, however, it is no longer accessible and the reference to i does not refer to that
block variable any longer.
Thus the declaration of i that is valid at the point in the program where the cout statement is, is the second
declaration of the variable, namely
int i = 5;
LESSON 15
Exercise 15.1
int main( )
{
int n, sum;
cout << "Up to what number do you want the sums of the odd numbers? ";
cin >> n;
sum = 0;
21
for (int i = 1; i <= n; i+=2) // we could also have i++ followed by
// if (i%2 == 1) in next line
{
sum += i;
cout << "Sum up to " << i << " is " << sum << endl;
}
return 0;
}
Exercise 15.2
int main( )
{
char c;
return 0;
}
Exercise 15.3
int main( )
{
int asciiValue;
return 0;
}
Exercise 15.4
//Ten in the bed (version for Lesson 15)
#include <iostream>
using namespace std;
int main( )
{
for (int num = 10; num > 1; num--)
{
cout << "There were " << num << " in the bed" << endl
22
<< "And the little one said:" << endl
<< "\"Roll over, roll over!\"" << endl
<< "So they all rolled over, " << endl
<< "And one fell out," << endl;
}
cout << "There was 1 in the bed" << endl
<< "And the little one said:" << endl
<< "\"Good night!\"" << endl << endl;
return 0;
}
LESSON 16
Exercise 16.1
//Calculates y as a function of x
#include <iostream>
using namespace std;
int main( )
{
int startVal, endVal, x, y;
Exercise 16.2
int main( )
{
int product;
// heading
for (int col = 1; col <= 9; col++)
cout << '\t' << col;
23
cout << endl;
//table
for (int row = 1; row <= 9; row++)
{
cout << row;
for (int col = 1; col <= row; col++)
{
product = row * col;
cout << '\t' << product;
}
cout << endl;
}
return 0;
}
LESSON 17
Exercise 17.1
//Lottery numbers
#include <iostream>
using namespace std;
int main( )
{
int num1, num2, num3, num4, num5, num6;
srand(time(0));
// output
24
cout << "The 6 random numbers are:" << endl;
cout << ' ' << num1 << ' ' << num2 << ' ' << num3
<< ' ' << num4 << ' ' << num5 << ' ' << num6 << endl << endl;
return 0;
}
Exercise 17.2
(i) y = (fabs(x)) * 2
= (fabs(-6.32) * 2
= 6.32 * 2
= 12.64
(ii) y = (2 * (pow(x,2))) - 1
= (2 * (pow(2,2))) - 1
= 2 * 4 - 1
= 8 - 1
= 7
z = (2 * (pow(x-1,2)))
= 2 * pow(1,2)
= 2 * 1
= 2
(iii) y = sqrt(fabs(x))
= sqrt(fabs(-4))
= sqrt(4)
= 2
(iv) z = sqrt(pow(x,2) + pow(y,2))
= sqrt(pow(3,2) + pow(4,2))
= sqrt(9 + 16)
= sqrt(25)
= 5
Exercise 17.3
//Pythagoras
#include <iostream>
#include <cmath>
using namespace std;
int main( )
{
float a,b,c;
cout << "Please enter the values of the ";
cout << "two shorter sides of the triangle: ";
cin >> b >> c;
a = sqrt(pow(b, 2) + pow(c, 2));
cout.setf(ios::fixed);
cout.precision(2);
cout << "The length of the longest side is " << a << endl;
return 0;
}
Exercise 17.4
int main( )
{
25
char c, cConverted;
return 0;
}
The function toupper changes lower case letters of the alphabet to the corresponding upper case letters. It does
not change upper case letters, digits or punctuation characters.
Exercise 17.5
//Shakespeare
#include <iostream>
using namespace std;
int main( )
{
const int NUMBER_OF_WORDS = 15; //number of words in a 'sentence'
char c;
int numberOfLetters;
srand(time(0));
return 0;
}
LESSON 18
Exercise 18.1
Function heading 5
26
Function call 14 The function is called inside the condition of the if statement
Exercise 18.2
int main( )
{
float var1, var2, var3;
return 0;
}
Exercise 18.3
// formula
float approximateTemp(float numberP)
{
return (numberP + 160)/4;
}
int main( )
{
float number, fahrTemperature, celsiusTemperature;
27
cout << "Please enter the number of cricket chirps per minute: ";
cin >> number;
fahrTemperature = approximateTemp(number);
celsiusTemperature = tempCelsius(fahrTemperature);
cout.setf(ios::fixed);
cout.precision(2);
cout << "The approximate temperature is ";
cout << fahrTemperature << " degrees F, or ";
cout << celsiusTemperature << " degrees C" << endl;
return 0;
}
Exercise 18.4
//Area of a triangle
#include <iostream>
#include <cmath>
using namespace std;
int main( )
{
float a, b, c, areaTriangle;
cout << "Please enter the lengths of the 3 sides of the triangle: ";
cin >> a >> b >> c;
cout << "The area of the triangle is " << areaTriangle << endl;
return 0;
}
Exercise 18.5
28
18 int main( )
19 {
20 float a, b, c, largest;
21 cout << ”Enter three numbers: ”;
22 cin>> a >> b >> c;
23 largest = max3(a, b, c);
24 cout << “The maximum is: “ << largest << endl;
25 return 0;
26 }
For the purposes of clarity, we included a separate box in the solution below in those variable diagrams which
depict a function returning a value.
a b c largest
Line 20 : ? ? ? ?
a b c largest
Line 22 : 4 5 3 ?
LESSON 19
Exercise 19.1
return answer;
}
29
int main( )
{
float limit, result;
int n, x;
cout << "Enter a limit for the calculations: ";
cin >> limit;
x = 2;
n = 1;
return 0;
}
Exercise 19.2
• Variable n is declared at the beginning of the program outside the declaration of all functions and is
accessible throughout the program, i.e. throughout all three functions. It is a global variable.
• Variable answer is declared at the beginning of the program and it is natural to think that it will be
accessible throughout the program, i.e. in all three functions. This is, however, not the case. In function
product we have another declaration of answer. This answer (declared in function product) is
accessible in product only (lines 16 to 20). It is actually a local variable of the function. All references to
answer inside product, will be to this local variable. The answer defined at the beginning of the program
will be accessible in functions sum and main. All references to answer inside sum and main, will be to this
global variable.
• In both function sum and function product, a variable i is declared. Both declarations are done inside for
loops. In both cases the variable will only be accessible inside the relevant for loop. Hence, in function sum,
the (local) variable i will be accessible in lines 9 and 10, and in function product, the (local) variable i will
be accessible in lines 17 and 18.
Exercise 19.3
// sum from 1 up to n
int sum(int n)
{
int s = 0;
for (int i = 1; i <= n; i++)
s += i;
return s;
}
// product from 1 up to n
int product(int n)
{
int p = 1;
for (int i = 2; i <= n; i++)
p *= i;
return p;
}
30
int main( )
{
int upperLimit, answerSum, answerProd;
answerSum = sum(upperLimit);
cout << "The sum of 1 up to " << upperLimit << " is "
<< answerSum << endl;
answerProd = product(upperLimit);
cout << "The product of 1 up to " << upperLimit << " is "
<< answerProd << endl;
return 0;
}
LESSON 20
Exercise 20.1
int main( )
{
int width, height;
cout << "Please enter the width and height of the rectangle: ";
cin >> width >> height;
displayFrame(width, height);
return 0;
}
Exercise 20.2
//Draws a tree
#include <iostream>
using namespace std;
int main( )
{
int size;
return 0;
}
Exercise 20.3
int main( )
{
int value, total, many, averageInt;
float average;
total = 0;
many = 0;
32
if (many > 0)
{
average = float(total)/many;
cout << "The average is " << average << endl;
averageInt = int(average + 0.5);
displayRow(averageInt, '+');
}
else
cout << "There were no values entered." << endl;
return 0;
}
LESSON 21
Exercise 21.1
int main( )
{
int count, total;
srand(time(0));
calcTotalDice(total);
count = 1;
while (total != 7)
{
calcTotalDice(total);
count++;
}
cout << "It took " << count << " throws ";
cout << "before 7 was thrown." << endl;
return 0;
}
Exercise 21.2
//Display a histogram for a series of values (version of lesson 21)
#include <iostream>
using namespace std;
int main( )
{
int value, total, many, averageInt;
float average;
total = 0;
many = 0;
if (many > 0)
{
average = float(total)/many;
cout << "The average is " << average << endl;
averageInt = int(average + 0.5);
displayRow(averageInt, '+');
}
else
cout << "There were no values entered." << endl;
return 0;
}
Exercise 21.3
int main( )
{
float radius, area, circumference;
34
cout << "The circumference of the circle is " << circumference << endl;
}
return 0;
}
Exercise 21.4
//Area and circumference of a circle (version 2)
#include <iostream>
using namespace std;
int main( )
{
float radius, area, circumference;
area = areaCircle(radius);
circumference = circumCircle(radius);
cout << "The area of the circle is " << area << endl;
cout << "The circumference of the circle is " << circumference << endl;
}
return 0;
}
LESSON 22
Exercise 22.1
int main( )
{
int i;
return 0;
}
Exercise 22.2
int main( )
{
int first, second;
return 0;
}
Exercise 22.3
//Three values are rotated
#include <iostream>
using namespace std;
int main( )
{
int first, second, third;
36
return 0;
}
LESSON 23
Exercise 23.1
Line 14 6
a b
Line 15 6 7
a b c
Line 16 6 7 8
Line 17->5 6 7 8 6 8
Line 7 6 7 8 16 8
Line 8 6 17 8 16 8
Line 9 6 17 8 16 18
a b c
Line 10->17 6 17 8
Exercise 23.2
a b c
Line 5 ? ? ?
a b c
Line 24 1 ? ?
a b c
Line 25 1 2 ?
a b c
Line 26 1 2 3
a|i b c j
Line 27->7 1 2 3 2
37
a|i b c j
Line 9 1 2 3 3
a|i b c j
Line 10 3 2 3 3
a|i b c j
Line 11 3 2 2 3
a b c
Line 12->27 3 2 2
a b|i c j
Line 28->14 3 2 2 2
a b|i [c] j c
Line 16 3 2 2 2 ?
a b|i [c] j c
Line 17 3 2 2 3 ?
a b|i [c] j c
Line 18 3 2 2 3 5
a b|i [c] j C
Line 19 3 10 2 3 5
a b c
Line 20->28 3 10 2
This program makes use of global variables. We hope, however, that after having worked through this exercise,
you will be too scared ever to use global variables! The variables a, b and c are declared as global variables in line
5 and are given values in lines 24 to 26. W hen function funcP is called in line 27, a is mapped onto i and b onto
j.
Because i is a reference parameter, we normally interpret it as a temporary name for variable a. Unfortunately it is
not so simple. Both variable a and variable i may be used in the function! (The reason is, of course, that a is
defined globally.) Any changes to i in function funcP will be reflected in the value of a (which is no surprise) and
any changes to a in function funcP will be reflected in the value of a and also in the value of i (this may be
surprising). Suppose we add the following statements to those of funcP between lines 8 and 9:
a += 2;
i += 3;
After the first of these two statements have been executed, the value of both a and i would be 3, and after the
second of these two statements have been executed, the value of both a and i would be 6.
Because j is a value parameter, we would expect to put square brackets around b in the variable diagram to
indicate that the variable is unaccessible. That is, however, not the case. Both variable b and variable j may be
used in the function! (The reason is, of course, that b is defined globally.) We do not put any brackets around it in
the diagram, because b does not have anything to do with j. Any changes to j will not be reflected in the value of b
(no surprise) but we may refer to b inside function funcP and change its value if we like (this may be surprising).
Suppose we add the following statements to those of funcP between lines 8 and 9:
b += 5;
38
j += 2;
After the first of these two statements have been executed, the value of b would be 7 and the value of j would still
be 2, and after the second of these two statements have been executed, the value of b would (still) be 7 and the
value of j would be 4.
Variable c does not play any role in the call to function funcP. However, because it is a global variable, it is
accessible inside the function - we may change its value inside function funcP. No brackets are used in the
variable diagram.
When control jumps back from function funcP to function main (12 → 27), the values of a, b and c are,
respectively, 3, 2 and 2. Now function funcQ is called. Here b is mapped onto i and c onto j.
Because i is a reference parameter, we normally interpret it as a temporary name for b. Unfortunately it is not so
simple. Both variable b and variable i may be used in the function. (The reason is, once again, that b is defined
globally.) Any changes to i in function funcQ will be reflected in the value of b (which is no surprise) and any
changes to b in function funcP will be reflected in the value of b and also in the value of i (this may be
surprising). Suppose we add the following statements to those of funcQ between lines 15 and 16:
b += 2;
i += 3;
After the first of these two statements have been executed, the value of both b and i would be 4, and after the
second of these two statements have been executed, the value of both b and i would be 7.
Because j is a value parameter, we would expect to put square brackets around c in the variable diagram to
indicate that the variable is unaccessible.It is, however, not the case. When the function is entered, the globally
defined variable c is still accessible. Then, in line 16 a variable c is declared as a local variable inside function
funcQ and this overrides the global declaration. The global c is now inaccessible in this function and that is the
reason for the square brackets around the globally defined c in the variable diagram of line 13. When c is altered in
the function, it has no influence on either j or the globally defined c.
So the moral of the story is: Avoid the use of global variables.
Exercise 23.3
Line 27 1
x y
Line 28 1 2
[x]|one [y]|two
Line 29->20 1 2
[x]|[one]|one [y]|[two]|two
Line 22->11 1 2
Line 13 1 2 ?
[x]|[one]|one [y]|[two]|two three
Line 14 1 2 1
Line 15 2 2 1
39
[x]|[one]|one [y]|[two]|two three
Line 16 2 1 1
Line 17->5 2 1 1 2 1
Line 7 2 1 1 3 1
Line 8 2 1 1 3 3
Line 9->17 2 1 1
[x]|one [y]|two
Line 18->22 2 1
x y
Line 23->29 2 1
In this exercise we have nested function calls. Look at how the temporary names of reference parameters are
indicated in the diagrams – we put square brackets around the names that are temporarily replaced. When the
function funcC is executed, we are dealing with value parameters. The names of all the other variables are
inaccessible and we make new copies of one and two.
The moral of this exercise is that you should use different names for the actual and formal parameters of a function.
LESSON 24
Exercise 24.1
// numbers[index] = numbers[0];
// numbers[0] = max;
40
// Output
cout << "Changed array:" << endl;
for (int j = 0; j < N; j++)
cout << numbers[j] << " ";
cout << endl;
return 0;
}
Exercise 24.2
//Displays the elements of an array in reverse order
#include <iostream>
using namespace std;
main( )
{
const int N = 10; // number of values in the array
float numbers[N];
// Input
cout << "Enter " << N << " floating point numbers separated by spaces:"
<< endl;
for (int j = 0; j < N; j++)
cin >> numbers[j];
return 0;
}
Exercise 24.3
main( )
{
bool ascending;
const int N = 20; //equal to the number of elements in the array
int numbers[] = {12, 15, 17, 23, 37, 40, 55, 54, 70, 77,
79, 80, 84, 86, 89, 91, 92, 100, 123, 126};
int index;
41
cout << "The value in position " << index << ", namely "
<< numbers[index] << ", is the first value out of order." << endl;
}
return 0;
}
Exercise 24.4
main( )
{
const int N = 10; // size of the two arrays
float array1[N], array2[N];
// Input
cout << "Enter " << N << " floating point numbers separated by spaces:"
<< endl;
for (int j = 0; j < N; j++)
cin >> array1[j];
cout << "The corresponding values of array2 and array1 are now the same."
<< endl;
return 0;
}
Exercise 24.5
int main( )
{
const int NUM_VALS = 15; // number of values to be generated and sorted
int values[NUM_VALS];
int nextVal, current;
srand(time(0));
// compares 'new value' with all values that are already sorted,
// starting at the last value so far and
// shifting every value larger than 'new value' one position to the right
while ((current >= 0) && (values[current] > nextVal))
{
values[current+1] = values[current];
current--;
}
values[current + 1] = nextVal; // inserts 'new value' at correct
// position
cout << "After the " << i+1 << "th value has been generated, "
42
<< "the sorted array looks as follows:" << endl;
for (int j = 0; j <= i; j++)
cout << values[j] << ' ';
cout << endl;
}
cout << endl << endl << "The final sorted array:" << endl;
for (int i = 0; i < NUM_VALS; i++)
cout << values[i] << " ";
cout << endl << endl;
return 0;
}
LESSON 25
Exercise 25.1
return false;
}
// output
void outputArray(const int a[])
{
for (int i = 0; i < N; i++)
cout << a[i] << " ";
43
cout << endl;
}
int main( )
{
int array[N]; // N was declared as a global constant int
number, smallestElement;
inputArray(array);
smallestElement = smallest(array);
cout << endl << "Smallest element in the array: "
<< smallestElement << endl;
reverseArray(array);
cout << endl << "Reversed array is:" << endl;
outputArray(array);
return 0;
}
Exercise 25.2
Run the program if you want to get the answer to the question. 1 indicates open and 0 indicates closed.
// investigate every j-th post box: close it if open, open it if closed void
openAndClose(bool a[], int j)
{
for (int i = j; i <= NUM_OF_BOXES; i += j)
a[i-1] = ! a[i-1];
// display status at this point: 1 indicates open and 0 indicates closed cout <<
endl << j << ":\t ";
for (int i = 0; i < NUM_OF_BOXES; i++)
cout << a[i];
}
int main( )
{
bool postBox[NUM_OF_BOXES]; // true if box is open, false if closed
return 0;
}
44
Exercise 25.3
// validate
for (int i = 0; i < NUM_QUESTIONS; i++)
while ((a[i] != 'T') && (a[i] != 'F'))
{
cout << endl << "Answer " << i+1 << " is not valid. Type it again: ";
cin >> a[i];
}
}
// calculate mark
int mark(const char correctAnswersP[], const char studentAnswersP[])
{
int m = 0;
for (int i = 0; i < NUM_QUESTIONS; i++)
if (correctAnswersP[i] == studentAnswersP[i])
m++;
return m;
}
int main( )
{
int result;
char correctAnswers[NUM_QUESTIONS];
char studentAnswers[NUM_QUESTIONS];
return 0;
}
LESSON 26
Exercise 26.1
45
const int N = 10; // size of two N x N matrices
// input values
void inputDataIntoSquareMatrix(int a[][N])
{
for (int i = 0; i < N; i++)
{
cout << "Enter " << N << " values for row " << i << ": ";
for (int j = 0; j < N; j++)
cin >> a[i][j];
cout << endl;
}
}
// determine whether matrix a is the transposition of matrix b
bool transposition(const int a[][N], const int b[][N])
{
for (int i = 0; i < N; i++)
for (int j = 0; j < N; j++)
if (a[i][j] != b[j][i])
return false;
return true;
}
int main( )
{
int matrixA[N][N], matrixB[N][N];
// input
cout << "FIRST MATRIX" << endl << endl;
inputDataIntoSquareMatrix(matrixA);
cout << endl << "SECOND MATRIX" << endl << endl;
inputDataIntoSquareMatrix(matrixB);
return 0;
}
Exercise 26.2
return sum;
}
// determine month and year with highest rainfall (first time)
// as well as number of times that this occurred
void getHighest(const float r[][NUM_MONTHS], float & highP,
int & yearP, int & monthP, int & nrTimesP)
{
// initialise
highP = -1;
yearP = -1;
monthP = -1;
nrTimesP = 0;
int main( )
{
float rainData[NUM_YEARS][NUM_MONTHS];
float total, annualAverage, monthlyAverage, maxRainfall;
int yearMax, monthMax, nrTimes;
cout.setf(ios::fixed);
cout.precision(2);
// input
inputRainData(rainData);
// total rainfall
total = totalRain(rainData);
// determine when and how many times highest monthly rainfall occurred
getHighest(rainData, maxRainfall, yearMax, monthMax, nrTimes);
47
// display result
cout << endl << "The maximum rainfall was " << maxRainfall << "mm." << endl;
cout << "It occurred in year " << FIRST_YEAR + yearMax
<< " and month " << monthMax+1 << " for the first time. " << endl;
cout << "It happened " << nrTimes << " time(s)." << endl << endl;
return 0;
}
Exercise 26.3
//Theatre reservations
#include <iostream>
using namespace std;
// mark 'num' seats in row 'r' with character 'marker', starting at seat 's'
void markSeats(char planP[][NUM_SEATS], char marker, int r, int s, int num)
{
for (int i = s-1; i < s-1 + num; i++)
planP[r][i] = marker;
}
// test whether there are 'num' unreserved seats in row r starting at seat s
// (seat index as on plan)
// and display a message if an error occurs
void checkIfValid(const char planP[][NUM_SEATS], int r, int s, int num,
bool & valid)
{
int lastNumber; // number of last ticket
char rowChar;
valid = true;
lastNumber = s + num - 1; //index as on plan
48
// Are too many tickets required?
if (lastNumber > NUM_SEATS)
{
cout << "PROBLEM: There are not " << num << " seats available here";
cout << endl;
valid = false;
}
// Is one of the required seats already reserved?
else
for (int i = s - 1; i < lastNumber; i++)
if (planP[r][i] == 'R')
{
cout << "PROBLEM: " << ROW_CHAR[r] << i+1 << " is already reserved";
cout << endl;
valid = false;
}
}
int main( )
{
char plan[NUM_ROWS][NUM_SEATS];
char row;
int numberOfTickets, seatNumber, rowNumber;
bool validBooking;
// headings
cout << "Theatre reservations: Rows A to E and seats 1 to 9"
<< endl << "To stop, type Q for row" << endl << endl;
// first reservation
cout << endl << "In which row do you want seats? ";
cin >> row; // index as on plan
// next reservation
displayPlan(plan);
cout << endl << "In which row do you want seats? ";
cin >> row;
}
return 0;
}
49
LESSON 27
Exercise 27.1
return upper;
}
int main( )
{
string sentence, newSentence;
return 0;
}
Exercise 27.2
int main( )
{
string namesAndSurname, initials;
int pos;
cout << "Please enter full names and surname, all separated by spaces: "
<< endl;
getline(cin, namesAndSurname, '\n');
initials = namesAndSurname[0];
pos = namesAndSurname.find(" "); // position of next space character
while (pos > 0)
{
initials = initials + namesAndSurname[pos+1];
pos = namesAndSurname.find(" ", pos+1); // position of next space
}
cout << "Initials are: " << initials << endl;
return 0;
}
Exercise 27.3
int main( )
{
string sentence, word;
int start, pos, lengthOfWord;
start = 0;
pos = sentence.find(" "); // finds position of first space character
return 0;
}
Exercise 27.4
We adapt the second version of the solution of Activity 27.c, namely the version where the string member function
replace is used. Note that ‘word’ in this context does not mean a stand-alone English word, but rather a (sub)string
of characters.
int main( )
{
string sentence, word1, word2;
int position, lengthSecondWord;
51
cout << "Enter a word (substring) to search for: ";
cin >> word1;
cout << "Enter a word (substring) to replace it with: ";
cin >> word2;
lengthSecondWord = word2.size( );
return 0;
}
LESSON 28
Exercise 28.1
//A time struct and its manipulation (add seconds to a specific time)
#include <iostream>
using namespace std;
struct Time
{
int hours, minutes, seconds;
};
int main( )
{
Time timeNow;
int toBeAdded;
cout << "Enter time. Give hours, minutes and seconds, "
<< "separated by blanks: ";
cin >> timeNow.hours >> timeNow.minutes >> timeNow.seconds;
cout << "How many seconds should be added? ";
cin >> toBeAdded;
changeTime(timeNow, toBeAdded);
cout << "New time is " << timeNow.hours << " " << timeNow.minutes
<< " " << timeNow.seconds << endl;
52
return 0;
}
Exercise 28.2
We have to:
Apart from getPassengerInfo we need at least two new functions. We called them getDeliveryInfo (for
point 2 above) and displayTag (for point 3 above). We also decided to write three other functions, namely
displayPassengerInfo that displays some of the user’s dialogue, displayChars that displays a row of
characters, and displayOneLine that displays one line of text.
We cheated a little bit in this program, particularly in the displayTag function. W e used the width member
function of cout, which you probably haven't seen yet. Like setf and precision, the width member
function can be used to specify how cout should display the values inserted in it. In particular, width sets the
number of columns that should be used for the next insertion into the cout stream, and fills up any unused places
on the left with blanks. Note that width only has a temporary effect, i.e. for the next use of cout only. For
subsequent cout statements, width is reset to the default (with no blanks inserted).
We used width because without it, you would have to use a number of messy if statements to determine how
many digits the mass field contains, to be able to display the correct number of spaces for the tag. (If you didn't
print a border for your tag, you wouldn't have had this problem.).
53
// users dialogue concerning luggage void
getDeliveryInfo(TagInfo & t)
{
// the information was correct: proceed
cout << "============" << endl;
cout << "We provide a FREE delivery service - up to 100 km from airport."
<< endl << "Would you like your luggage delivered (Y/N)? ";
cin >> t.choice;
if (toupper(t.choice) == 'Y')
{
// luggage has to be delivered
cin.get( ); // necessary between cin >> and getline
cout << "Enter the address of your final destination (four lines):"
<< endl;
for (int i = 0; i < 4; i++)
getline(cin, t.address[i], '\n');
cout << "Thank you!" << endl
<< "Your luggage will be delivered within 3 hours of arrival."
<< endl << "============" << endl << endl;
}
}
// display a row of the same characters void
displayChars(char c, int i)
{
for (int j = 0; j < i; j++)
cout << c;
}
// display one line: start with *, then the information,
// then the correct number of blanks, followed by *,
// and move to next line
void displayOneLine(string info)
{
cout << "* " << info;
displayChars(' ', TAG_WIDTH - 4 - info.size( ));
cout << "*" << endl;
}
// display information to be printed on tag void
displayTag(TagInfo t)
{
displayChars('*', TAG_WIDTH);
cout << endl;
displayOneLine("Name: " + t.name);
displayOneLine("Flight: " + t.flight);
displayOneLine("Destination: " + t.destination);
if (toupper(t.choice) != 'Y')
displayOneLine("*** PICK UP AT AIRPORT ***");
else
{
displayOneLine("BAGGAGE TO BE DELIVERED TO:");
for (int i = 0; i < 4; i++)
displayOneLine(" " + t.address[i]);
}
displayChars('*', TAG_WIDTH);
cout << endl;
}
54
int main( )
{
TagInfo passenger; char correct;
getPassengerInfo(passenger);
displayPassengerInfo(passenger);
return 0;
}
LESSON 29
Exercise 29.1
struct ItemInfo
{
string description;
int nrProduced, nrSold, difference;
};
// input information of one item
void inputData(ItemInfo & thisItem, int nr)
{
cin.get( ); // necessary between cin and getline
cout << endl << "Item " << nr+1 << endl << "Description: ";
getline(cin, thisItem.description, '\n');
cout << "Number produced: ";
cin >> thisItem.nrProduced;
cout << "Number sold: ";
cin >> thisItem.nrSold;
thisItem.difference = thisItem.nrProduced - thisItem.nrSold;
}
// output information of one item
void outputData(ItemInfo thisItem)
{
cout << thisItem.description;
cout << "\t\t" << thisItem.nrProduced;
cout << "\t\t" << thisItem.nrSold;
cout << "\t\t" << thisItem.difference << endl;
}
int main( )
{
int n;
ItemInfo itemData[MAX_ITEMS];
55
cout << "How many types of items (maximum " << MAX_ITEMS << ")? ";
cin >> n;
return 0;
}
Exercise 29.2
You will see that we made three additional changes to the version in the Study Guide, namely we used i + 1
(instead of i) in the relevant cout statements to indicate the number of the student or the number of the
assignment. The reason is to have a better interface on the screen - humans normally count from 1 and not from 0.
struct Student
{
string name, studNo;
int marks[NUM_MARKS];
float average;
};
LESSON 30
Exercise 30.1
We have three member functions, namely inputData, displayData and average. Only inputData is a
mutator. The other two are inspectors - they do not alter the data.
#include <iostream>
#include <string>
using namespace std;
class Student
{
public:
void inputData( );
void displayData( ) const;
float average( ) const;
private:
string name, studNo;
int marks[4];
};
// input information of one student
57
void Student::inputData( )
{
cout << "Enter the student's information" << endl;
cout << "Student number: ";
cin >> studNo;
cout << "Name: ";
cin >> name;
cout << "Marks:" << endl;
for (int i = 0; i < NUM_MARKS; i++)
{
cout << "Assignment " << i << ": ";
cin >> marks[i];
}
}
// display information of one student
void Student::displayData( ) const
{
cout << endl;
cout << "Student number: " << studNo << endl;
cout << "Name: " << name << endl;
cout << "Marks:" << endl;
for (int i = 0; i < NUM_MARKS; i++)
cout << " Assignment " << i << ": " << marks[i] << endl;
}
// find average mark of one student
float Student::average( ) const
{
int total = 0;
for (int i = 0; i < NUM_MARKS; i++)
total += marks[i];
return 0;
}
Exercise 30.2
Note that it is necessary to pass account1 as a parameter when we call inputTransactions. Also note that it
should be a reference parameter - instances of classes are passed in a way similar to structs, not like arrays.
58
// Processes a banking account and displays a monthly statement
// Version 2 ( exercise 2)
#include <iostream>
using namespace std;
struct Transaction
{
char type;
float amount;
};
Account::Account( )
{
balance = 0;
numTransacts = 0;
feeTotal = 0;
}
void Account::deposit(float a)
{
balance += a;
feeTotal += DEPOSIT_FEE;
balance -= DEPOSIT_FEE;
transacts[numTransacts].type = 'D';
transacts[numTransacts].amount = a;
numTransacts++;
}
float Account::balanceEnquiry( )
{
feeTotal += BALANCE_FEE; balance -=
BALANCE_FEE;
transacts[numTransacts].type = 'B';
transacts[numTransacts].amount = 0;
numTransacts++;
return balance;
}
void Account::withdrawal(float a)
{
balance -= a;
if (balance >= 0)
{
feeTotal += WITHDRAWAL_FEE;
balance -= WITHDRAWAL_FEE;
59
}
else
{
feeTotal += OVERDRAWN_FEE;
balance -= OVERDRAWN_FEE;
}
transacts[numTransacts].type = 'W';
transacts[numTransacts].amount = a;
numTransacts++;
}
void Account::displayStatement( ) const
{
cout << endl << "Monthly Statement" << endl;
cout << "=================" << endl;
cout.setf(ios::fixed);
cout.precision(2);
for (int i = 0; i < numTransacts; i++)
{
switch (transacts[i].type)
{
case 'D':
cout << "Deposit\t\tR" << transacts[i].amount << endl;
break;
case 'B':
cout << "Balance enquiry" << endl;
break;
case 'W':
cout << "Withdrawal\tR" << transacts[i].amount << endl;
break;
}
}
cout << "Total Fee\tR" << feeTotal << endl;
cout << "---------------------------------" << endl;
cout << "Closing balance\tR" << balance << endl;
}
cout << "Enter the transactions for the month" << endl;
cout << "(D)eposit, (B)alance enquiry, (W)ithdrawal, E(X)it:"
<< endl;
cin >> type;
while (toupper(type) != 'X')
{
switch(toupper(type))
{
case 'D':
cin >> amount;
accountP.deposit(amount);
break;
case 'B':
accountP.balanceEnquiry( );
break;
case 'W':
cin >> amount;
accountP.withdrawal(amount);
}
cin >> type;
}
}
int main( )
60
{
Account account1;
inputTransactions(account1);
cout << endl;
account1.displayStatement( );
return 0;
}
Exercise 30.3
//Swimmingpool
#include <iostream>
using namespace std;
class SwimmingPool
{
public:
SwimmingPool(int l, int w, int d, int s);
int volume( ) const;
private:
int length, width, deepDepth, shallowDepth;
};
SwimmingPool::SwimmingPool(int l, int w, int d, int s)
{
length = l; width
= w; deepDepth =
d; shallowDepth =
s;
}
int SwimmingPool::volume( ) const
// The volume of the pool consists of a cube plus a wedge.
// The cube's dimensions are l x w x s.
// The wedge is l x w if considered from above. The side view is a
// triangle with height (d-s),
// and length l (perpendicular to the height).
{
float v;
int main( )
{
int len, wid, deepDep, shallowDep, vol;
cout << "Please give the dimensions of the swimming pool." << endl;
cout << "Length: ";
cin >> len;
cout << "Width: ";
cin >> wid;
cout << "Depth at deep end: ";
cin >> deepDep;
cout << "Depth at shallow end: ";
cin >> shallowDep;
SwimmingPool pool(len, wid, deepDep, shallowDep);
vol = pool.volume( );
cout << endl << "The volume is " << vol << endl << endl;
61
return 0;
}
Exercise 30.4
At this stage you will not be able to test your program because of the missing implementation of the member
functions.
class WavSound
{
public:
WavSound( );
void loadFile(string fName);
bool isLoaded( ) const;
void play( );
void stop( );
void rewind( );
private:
bool loaded;
string fileName;
};
int main( )
{
WavSound sound1;
char option;
string fName;
cout << "This program plays .wav sound files" << endl;
cout << "= = = = = = = = = = = = = = = = = =" << endl;
cout << "Choose one of the following options:" << endl;
cout << "(L)oad, (P)lay, (S)top, (R)ewind, e(X)it: ";
cin >> option;
option = toupper(option);
while (option != 'X')
{
switch (option)
{
case 'L':
cout << "Enter the name of a .wav file: ";
cin >> fName;
sound1.loadFile(fName);
if (!sound1.isLoaded( ))
cout << " ** The file " << fName << " was not found **" << endl;
break;
case 'P':
if (sound1.isLoaded( ))
sound1.play( );
else
cout << "** You must load a file first **" << endl;
break;
case 'S':
sound1.stop( );
break;
case 'R':
sound1.rewind( );
}
62
cout << "(L)oad, (P)lay, (S)top, (R)ewind, e(X)it: ";
cin >> option;
option = toupper(option);
}
return 0;
}
©
UNISA
2018
63