C++ Exercises
Time to practise! Each exercise below comes with a starter program that compiles and runs, but does not do the job yet. Replace the TODO parts, press ▶ Run, and compare your result with the expected output. The output block under each starter shows what the unfinished starter prints.
Tip: Try each exercise for at least ten minutes before opening the solution. Struggling a little is how the knowledge sticks — and there is usually more than one correct solution.
| # | Exercise | Practises |
|---|---|---|
| 1 | FizzBuzz | Loops, if/else, % |
| 2 | Reverse and palindrome | Strings, functions |
| 3 | Statistics of a vector | Vectors, structs, loops |
| 4 | Temperature table | For loops, <iomanip> |
| 5 | Word frequencies | Maps, string streams |
| 6 | A Rectangle class | Classes, const methods, operator overloading |
| 7 | Generic largest() | Templates |
| 8 | Recursive helpers | Recursion |
Exercise 1: FizzBuzz
Print the numbers from 1 to 15, but print Fizz instead of multiples of 3, Buzz instead of multiples of 5, and FizzBuzz for numbers that are multiples of both.
#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 15; i++) {
// TODO: print "Fizz", "Buzz", "FizzBuzz" or the number
cout << i << "\n";
}
}1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Expected output when solved:
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzzHint: Test the "both" case first —
i % 15 == 0— otherwise 15 would be caught by theFizzbranch.
Show solution
#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 15; i++) {
if (i % 15 == 0) {
cout << "FizzBuzz\n";
} else if (i % 3 == 0) {
cout << "Fizz\n";
} else if (i % 5 == 0) {
cout << "Buzz\n";
} else {
cout << i << "\n";
}
}
}Exercise 2: Reverse and palindrome
Complete reverseWord, which returns the string backwards, and isPalindrome, which returns true when a word reads the same in both directions.
#include <iostream>
#include <string>
using namespace std;
string reverseWord(const string& s) {
// TODO: build and return the reversed string
return s;
}
bool isPalindrome(const string& s) {
// TODO: use reverseWord
return false;
}
int main() {
for (string w : {"level", "planet", "noon"}) {
cout << w << " -> " << reverseWord(w)
<< (isPalindrome(w) ? " (palindrome)" : "") << "\n";
}
}level -> level
planet -> planet
noon -> noon
Expected output when solved:
level -> level (palindrome)
planet -> tenalp
noon -> noon (palindrome)Hint: Loop from the last index down to 0 and append each character to a new string. Careful:
s.size() - 1is unsigned, so convert it tointbefore counting down.
Show solution
#include <iostream>
#include <string>
using namespace std;
string reverseWord(const string& s) {
string result;
for (int i = static_cast<int>(s.size()) - 1; i >= 0; i--) {
result += s[i];
}
return result;
}
bool isPalindrome(const string& s) {
return s == reverseWord(s);
}
int main() {
for (string w : {"level", "planet", "noon"}) {
cout << w << " -> " << reverseWord(w)
<< (isPalindrome(w) ? " (palindrome)" : "") << "\n";
}
}Exercise 3: Statistics of a vector
Fill in computeStats so that it returns the smallest value, the largest value and the average of the vector.
#include <iostream>
#include <vector>
using namespace std;
struct Stats {
int min;
int max;
double average;
};
Stats computeStats(const vector<int>& v) {
Stats s{0, 0, 0};
// TODO: fill in min, max and average
return s;
}
int main() {
vector<int> data = {14, 3, 27, 8, 19, 5};
Stats s = computeStats(data);
cout << "min: " << s.min << "\n";
cout << "max: " << s.max << "\n";
cout << "average: " << s.average << "\n";
}min: 0
max: 0
average: 0
Expected output when solved:
min: 3
max: 27
average: 12.6667Hint: Start
minandmaxat the first element. Convert the sum todoublebefore dividing, or you will get integer division.
Show solution
#include <iostream>
#include <vector>
using namespace std;
struct Stats {
int min;
int max;
double average;
};
Stats computeStats(const vector<int>& v) {
Stats s{v[0], v[0], 0};
int sum = 0;
for (int x : v) {
if (x < s.min) s.min = x;
if (x > s.max) s.max = x;
sum += x;
}
s.average = static_cast<double>(sum) / v.size();
return s;
}
int main() {
vector<int> data = {14, 3, 27, 8, 19, 5};
Stats s = computeStats(data);
cout << "min: " << s.min << "\n";
cout << "max: " << s.max << "\n";
cout << "average: " << s.average << "\n";
}Exercise 4: Temperature table
Print a table converting Celsius to Fahrenheit for -10, 0, 10, … 40 degrees. Each column is right-aligned with setw, and Fahrenheit values have one decimal place.
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
cout << fixed << setprecision(1);
cout << setw(8) << "Celsius" << setw(12) << "Fahrenheit" << "\n";
// TODO: loop from -10 to 40 in steps of 10 and print each row
} Celsius Fahrenheit
Expected output when solved:
Celsius Fahrenheit
-10 14.0
0 32.0
10 50.0
20 68.0
30 86.0
40 104.0Hint: F = C × 9 / 5 + 32. Use
9.0instead of9so the calculation happens in floating point.
Show solution
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
cout << fixed << setprecision(1);
cout << setw(8) << "Celsius" << setw(12) << "Fahrenheit" << "\n";
for (int c = -10; c <= 40; c += 10) {
double f = c * 9.0 / 5.0 + 32;
cout << setw(8) << c << setw(12) << f << "\n";
}
}Exercise 5: Word frequencies
Count how often each word appears in text. Print every word that occurs more than once, then the number of distinct words.
#include <iostream>
#include <map>
#include <sstream>
#include <string>
using namespace std;
int main() {
string text = "to be or not to be that is the question to ask";
map<string, int> freq;
// TODO: split text into words and count them in freq
for (const auto& [w, n] : freq) {
if (n > 1) cout << w << ": " << n << "\n";
}
cout << "distinct words: " << freq.size() << "\n";
}distinct words: 0
Expected output when solved:
be: 2
to: 3
distinct words: 9Hint: Read words with
istringstreamand>>, thenfreq[word]++— missing keys start at 0.
Show solution
#include <iostream>
#include <map>
#include <sstream>
#include <string>
using namespace std;
int main() {
string text = "to be or not to be that is the question to ask";
map<string, int> freq;
istringstream in(text);
string word;
while (in >> word) {
freq[word]++;
}
for (const auto& [w, n] : freq) {
if (n > 1) cout << w << ": " << n << "\n";
}
cout << "distinct words: " << freq.size() << "\n";
}Exercise 6: A Rectangle class
Give Rectangle the methods area(), perimeter() and isSquare(), and overload operator<< so a rectangle prints as Rectangle(3 x 4). Then print both rectangles with their area and perimeter, marking squares.
#include <iostream>
using namespace std;
class Rectangle {
public:
Rectangle(double w, double h) : width(w), height(h) {}
// TODO: area(), perimeter(), isSquare() and operator<<
double getWidth() const { return width; }
private:
double width;
double height;
};
int main() {
Rectangle a(3, 4), b(5, 5);
cout << a.getWidth() << " " << b.getWidth() << "\n";
}3 5
Expected output when solved:
Rectangle(3 x 4) area=12 perimeter=14
Rectangle(5 x 5) area=25 perimeter=20 squareHint: Make the three methods
const. Declareoperator<<as afriendso it can read the private members.
Show solution
#include <iostream>
using namespace std;
class Rectangle {
public:
Rectangle(double w, double h) : width(w), height(h) {}
double area() const { return width * height; }
double perimeter() const { return 2 * (width + height); }
bool isSquare() const { return width == height; }
friend ostream& operator<<(ostream& os, const Rectangle& r) {
return os << "Rectangle(" << r.width << " x " << r.height << ")";
}
private:
double width;
double height;
};
int main() {
Rectangle a(3, 4), b(5, 5);
for (const Rectangle& r : {a, b}) {
cout << r << " area=" << r.area() << " perimeter=" << r.perimeter()
<< (r.isSquare() ? " square" : "") << "\n";
}
}Exercise 7: Generic largest()
Turn largest into a function template so it works for int, double and string vectors, then uncomment the last two lines in main.
#include <iostream>
#include <string>
#include <vector>
using namespace std;
// TODO: turn this into a function template that works for any type
int largest(const vector<int>& items) {
int best = items[0];
for (int item : items) {
if (item > best) best = item;
}
return best;
}
int main() {
cout << largest(vector<int>{4, 17, 9}) << "\n";
// cout << largest(vector<double>{2.5, -1.0, 2.75}) << "\n";
// cout << largest(vector<string>{"pear", "apple", "plum"}) << "\n";
}17
Expected output when solved:
17
2.75
plumHint: Replace
intby a type parameterTeverywhere it refers to the element type; keep the loop identical.
Show solution
#include <iostream>
#include <string>
#include <vector>
using namespace std;
template <typename T>
T largest(const vector<T>& items) {
T best = items[0];
for (const T& item : items) {
if (item > best) best = item;
}
return best;
}
int main() {
cout << largest(vector<int>{4, 17, 9}) << "\n";
cout << largest(vector<double>{2.5, -1.0, 2.75}) << "\n";
cout << largest(vector<string>{"pear", "apple", "plum"}) << "\n";
}Exercise 8: Recursive helpers
Implement gcd(a, b) with Euclid's algorithm (gcd(a, 0) = a, otherwise gcd(b, a % b)) and sumDigits(n), which adds the decimal digits of n — both recursively.
#include <iostream>
using namespace std;
int gcd(int a, int b) {
// TODO: recursive Euclidean algorithm
return 1;
}
int sumDigits(int n) {
// TODO: recursive digit sum
return 0;
}
int main() {
cout << "gcd(48, 18) = " << gcd(48, 18) << "\n";
cout << "gcd(17, 5) = " << gcd(17, 5) << "\n";
cout << "sumDigits(98765) = " << sumDigits(98765) << "\n";
}gcd(48, 18) = 1
gcd(17, 5) = 1
sumDigits(98765) = 0
Expected output when solved:
gcd(48, 18) = 6
gcd(17, 5) = 1
sumDigits(98765) = 35Hint: For
sumDigits, the base case is a single digit (n < 10); otherwise add the last digitn % 10to the sum of the restn / 10.
Show solution
#include <iostream>
using namespace std;
int gcd(int a, int b) {
if (b == 0) return a;
return gcd(b, a % b);
}
int sumDigits(int n) {
if (n < 10) return n;
return n % 10 + sumDigits(n / 10);
}
int main() {
cout << "gcd(48, 18) = " << gcd(48, 18) << "\n";
cout << "gcd(17, 5) = " << gcd(17, 5) << "\n";
cout << "sumDigits(98765) = " << sumDigits(98765) << "\n";
}Test yourself
In FizzBuzz, why must the i % 15 == 0 test come first?
- It is faster
- Otherwise multiples of 15 would match the Fizz (or Buzz) branch first
- The compiler requires it
- It does not matter
Why does computeStats convert the sum to double before dividing?
- To avoid integer division truncating the average
- Because vectors only hold doubles
- To make it faster
- It is not necessary
What is the base case of the recursive gcd(a, b)?
- a == 0
- b == 0, returning a
- a == b
- a % b == 1