C++144 exercises

C++ Exercises with Answers

Practise C++ with 144 interactive exercises: multiple choice, fill-in-the-blank, output prediction and debugging. Every exercise gives instant feedback, a hint and the full solution.

Score0/ 144

1Introduction

Read the lesson
Fill in the blankseasyIntroduction

Complete the line so it prints Ready and ends the line.

cout  "Ready" << ;
Predict the outputeasyIntroduction

What does this print?

cout << "Score: " << 4 * 5 << endl;
Multiple choicemediumIntroduction

Which line must a program include to use cout?

Predict the outputmediumIntroduction

What does this print?

cout << 9 / 4 << " " << 9 % 4 << endl;
Multiple choicemediumIntroduction

What does return 0; at the end of main mean?

2Variables & Input

Read the lesson
Fill in the blankseasyVariables & Input

Complete the declarations.

 lives = 3;
 hero = "Nova";
Predict the outputeasyVariables & Input

What does this print?

int a = 10;
a = a + 5;
a = a * 2;
cout << a;
Predict the outputmediumVariables & Input

What does this print?

int x = 7;
int y = 2;
cout << x / y << " " << (double)x / y;
Multiple choicemediumVariables & Input

Which line reads a full sentence, including spaces, into s?

Predict the outputmediumVariables & Input

What does this print?

auto x = 5 / 2;
auto y = 5 / 2.0;
cout << x << " " << y << endl;

3Operators & Math

Read the lesson
Fill in the blankseasyOperators & Math

Complete the code so it prints the remainder of 20 divided by 6.

cout << 20  6 << endl;
Predict the outputeasyOperators & Math

What does this print?

cout << 11 / 4 << endl;
Predict the outputmediumOperators & Math

What does this print?

int x = 10;
x -= 4;
x *= 3;
cout << x << endl;
Multiple choicemediumOperators & Math

Which expression gives 2.5?

Multiple choicehardOperators & Math

Why is int big = 2147483647; big++; a problem in C++?

Fill in the blankseasyStrings

Complete the code so it prints the number of characters in city.

string city = "Lisbon";
cout << city.();
Predict the outputeasyStrings

What does this print?

string s = "Computer";
cout << s.substr(3, 3);
Predict the outputmediumStrings

What does this print?

string s = "banana";
s.replace(0, 1, "B");
s.erase(3);
cout << s;
Multiple choicemediumStrings

What does find return when the text isn't found?

Predict the outputhardStrings

What does this print?

cout << stoi("42abc") + 1;
Fill in the blankseasyif / else

Complete the code so it prints "Freezing" when temp is 0 or below.

int temp = -3;
 (temp  0) {
    cout << "Freezing";
}
Predict the outputeasyif / else

What does this print?

int x = 4;
if (x > 5) cout << "A";
else if (x > 3) cout << "B";
else cout << "C";
Predict the outputmediumif / else

What does this print?

int n = 2;
switch (n) {
    case 1: cout << "one ";
    case 2: cout << "two ";
    case 3: cout << "three ";
}
Multiple choicemediumif / else

Which condition is true when x is between 1 and 10, exclusive?

Predict the outputmediumif / else

What does this print?

int n = 7;
cout << (n % 2 == 0 ? "even" : "odd") << endl;
Fill in the blankseasyLoops

Complete the loop so it prints 1 to 5.

 (int i = 1; i <= 5; i) {
    cout << i << " ";
}
Predict the outputeasyLoops

What does this print?

for (int i = 10; i > 0; i -= 3) {
    cout << i << " ";
}
Predict the outputmediumLoops

How many stars does this print?

for (int a = 0; a < 3; a++)
    for (int b = 0; b < 4; b++)
        cout << "*";
Multiple choicemediumLoops

Which loop is best for a menu that must appear at least once?

Predict the outputmediumLoops

What does this print?

for (int i = 0; i < 10; i++) {
    if (i == 4) break;
    if (i % 2 == 1) continue;
    cout << i << " ";
}
Fill in the blankseasyFunctions

Complete the function so it returns the larger of two ints.

 maxOf(int a, int b) {
     a > b ? a : b;
}
Predict the outputeasyFunctions

What does this print?

int add(int a, int b = 5) { return a + b; }
// in main:
cout << add(1) << " " << add(1, 1);
Predict the outputmediumFunctions

What does this print?

void bump(int& n) { n++; }
// in main:
int x = 3;
bump(x);
bump(x);
cout << x;
Multiple choicemediumFunctions

What does const string& name mean for a parameter?

Multiple choicehardFunctions

Which declaration lets a function change the caller's variable?

8Arrays & Vectors

Read the lesson
Fill in the blankseasyArrays & Vectors

Complete the code to add 42 to the end of the vector.

vector<int> v;
v.(42);
Predict the outputeasyArrays & Vectors

What does this print?

vector<char> letters = {'c', 'o', 'd', 'e'};
cout << letters[1] << letters.size();
Predict the outputmediumArrays & Vectors

What does this print?

vector<int> v = {1, 2, 3};
for (int& x : v) x = x * 10;
v.pop_back();
for (int x : v) cout << x << " ";
Multiple choicemediumArrays & Vectors

What does v.at(10) do if v has only 3 items?

Predict the outputmediumArrays & Vectors

What does this print?

vector<int> v = {3, 1, 4};
v.push_back(1);
cout << v.size() << " " << v.back() << endl;
Fill in the blankseasyRecursion

Complete the base case so the function stops at zero.

int sumTo(int n) {
    if (n == ) return 0;
    return n + sumTo(n - 1);
}
Predict the outputeasyRecursion

Using the lesson's factorial function, what does factorial(4) return?

Predict the outputmediumRecursion

What does this print?

int f(int n) {
    if (n == 0) return 0;
    return 2 + f(n - 1);
}
cout << f(5) << endl;
Multiple choicemediumRecursion

What happens when recursion never reaches a base case?

Multiple choicehardRecursion

Why is naive recursive Fibonacci slow?

10Formatting & Streams

Read the lesson
Fill in the blankseasyFormatting & Streams

Complete the code so the value is printed with exactly two decimal places.

cout <<  << setprecision(2) << 7.5 << endl;
Predict the outputeasyFormatting & Streams

What does this print?

cout << "[" << setw(5) << 42 << "]" << endl;
Predict the outputmediumFormatting & Streams

What does this print?

cout << setfill('*') << setw(6) << left << "ok" << endl;
Multiple choicemediumFormatting & Streams

Which manipulator affects only the next value printed?

Multiple choicehardFormatting & Streams

How do you split "a;b;c" into pieces in C++?

11Structs & Enums

Read the lesson
Fill in the blankseasyStructs & Enums

Complete the struct definition.

 Point {
    int x;
    int y;
}
Predict the outputeasyStructs & Enums

What does this print?

struct Box { int w; int h; };
Box b{3, 4};
b.w = 5;
cout << b.w * b.h;
Multiple choicemediumStructs & Enums

How should a function that only reads a large struct take it?

Predict the outputmediumStructs & Enums

What does this print?

enum class Level { Low, Mid, High };
cout << static_cast<int>(Level::High);
Multiple choicehardStructs & Enums

What's the only difference between struct and class in C++?

Fill in the blankseasyPointers

Complete the code so p stores the address of age.

int age = 20;
int* p = age;
Predict the outputeasyPointers

What does this print?

int a = 8;
int* p = &a;
*p = *p * 2;
cout << a;
Predict the outputmediumPointers

What does this print?

int arr[4] = {5, 10, 15, 20};
int* p = arr;
cout << *(p + 3) << " " << *p;
Multiple choicemediumPointers

Which line correctly reads the name through a pointer to a struct?

Multiple choicehardPointers

When is a pointer a better choice than a reference?

13Classes & Objects

Read the lesson
Fill in the blankseasyClasses & Objects

Complete the class so name can only be used inside the class.

class Pet {
:
    string name;
:
    Pet(const string& n) : name(n) {}
};
Predict the outputeasyClasses & Objects

What does this print?

class Counter {
    int n = 0;
public:
    void add() { n += 2; }
    int get() const { return n; }
};
Counter a, b;
a.add(); a.add(); b.add();
cout << a.get() << " " << b.get();
Multiple choicemediumClasses & Objects

What is a member initializer list?

Multiple choicemediumClasses & Objects

What does const after a member function's brackets mean?

Predict the outputhardClasses & Objects

In what order are messages printed when an object made in a block reaches the block's closing brace?

14Maps & Sets (STL)

Read the lesson
Fill in the blankseasyMaps & Sets (STL)

Complete the code so it stores a score for "Ana".

map<string, int> scores;
scores.({"Ana", 82});
Predict the outputeasyMaps & Sets (STL)

What does this print?

set<int> s = {5, 1, 5, 3};
cout << s.size();
Predict the outputmediumMaps & Sets (STL)

What does this print?

map<string, int> m;
cout << m["x"] << " " << m.size();
Multiple choicemediumMaps & Sets (STL)

Which container gives fast lookups by key with no particular order?

Multiple choicehardMaps & Sets (STL)

What does m.find(k) != m.end() check?

15Algorithms & Lambdas

Read the lesson
Fill in the blankseasyAlgorithms & Lambdas

Complete the call that sorts the whole vector.

sort(v.(), v.end());
Predict the outputeasyAlgorithms & Lambdas

What does this print?

vector<int> v = {3, 8, 1, 8};
cout << count(v.begin(), v.end(), 8) << endl;
Predict the outputmediumAlgorithms & Lambdas

What does this print?

vector<int> v = {4, 9, 2};
cout << accumulate(v.begin(), v.end(), 10) << endl;
Multiple choicemediumAlgorithms & Lambdas

What does [&total] mean in a lambda?

Multiple choicehardAlgorithms & Lambdas

Why does remove_if need to be followed by erase?

16Exceptions

Read the lesson
Fill in the blankseasyExceptions

Complete the code so it throws an error for a negative age.

if (age < 0)  invalid_argument("Age can't be negative");
Multiple choiceeasyExceptions

How should exceptions usually be caught?

Predict the outputmediumExceptions

What does this print?

try {
    cout << "A";
    throw runtime_error("x");
    cout << "B";
} catch (const exception& e) {
    cout << "C";
}
cout << "D" << endl;
Multiple choicemediumExceptions

Which call throws out_of_range for an invalid index?

Multiple choicehardExceptions

What happens to local objects when an exception leaves a function?

17Files (fstream)

Read the lesson
Fill in the blankseasyFiles (fstream)

Complete the code that writes a line to a file.

 out("notes.txt");
out  "Hello file" << endl;
Multiple choiceeasyFiles (fstream)

Which mode adds to the end of an existing file?

Predict the outputmediumFiles (fstream)

A file contains 3 4 5. What does this print?

ifstream in("nums.txt");
int x, sum = 0;
while (in >> x) sum += x;
cout << sum;
Multiple choicemediumFiles (fstream)

Why is while (!in.eof()) a bad loop condition?

Predict the outputhardFiles (fstream)

What does this print?

stringstream ss("red,green,blue");
string part;
getline(ss, part, ',');
getline(ss, part, ',');
cout << part;

18Inheritance & Polymorphism

Read the lesson
Fill in the blankseasyInheritance & Polymorphism

Complete the line so Car inherits publicly from Vehicle.

class Car :  Vehicle {
};
Fill in the blanksmediumInheritance & Polymorphism

Complete the base class so derived classes can override sound().

class Animal {
public:
     string sound() const { return "..."; }
};
Predict the outputmediumInheritance & Polymorphism

What does this print?

struct A { virtual string hi() const { return "A"; } virtual ~A() = default; };
struct B : A { string hi() const override { return "B"; } };
// in main:
B b;
const A& ref = b;
cout << ref.hi();
Multiple choicemediumInheritance & Polymorphism

What makes a class abstract?

Multiple choicehardInheritance & Polymorphism

What is object slicing?

19Operator Overloading

Read the lesson
Fill in the blankseasyOperator Overloading

Complete the function name that overloads the + operator.

Vec2 (const Vec2& o) const {
    return {x + o.x, y + o.y};
}
Multiple choiceeasyOperator Overloading

Why must operator<< for printing be a non-member function?

Predict the outputmediumOperator Overloading

Using the lesson's Vec2, what does cout << Vec2{1, 2} + Vec2{3, 4}; print?

Multiple choicemediumOperator Overloading

What should operator+= return?

Multiple choicehardOperator Overloading

Which operator do std::sort and std::set use by default?

20Headers, Files & CMake

Read the lesson
Fill in the blankseasyHeaders, Files & CMake

Complete the first line of a header so it can't be included twice.

#pragma 
double circleArea(double radius);
Multiple choiceeasyHeaders, Files & CMake

Where do function bodies usually go?

Multiple choicemediumHeaders, Files & CMake

What does "undefined reference to geo::circleArea(double)" usually mean?

Multiple choicemediumHeaders, Files & CMake

Which include style is for your own project headers?

Multiple choicehardHeaders, Files & CMake

Why should a header never contain using namespace std;?

21Smart Pointers

Read the lesson
Fill in the blankseasySmart Pointers

Complete the line that creates a heap object owned by a unique_ptr.

auto p = <int>(42);
Multiple choiceeasySmart Pointers

What does a unique_ptr do when it's destroyed?

Predict the outputmediumSmart Pointers

What does this print?

auto a = make_shared<int>(1);
auto b = a;
auto c = b;
cout << a.use_count();
Multiple choicemediumSmart Pointers

How do you transfer ownership from one unique_ptr to another?

Multiple choicehardSmart Pointers

What problem does weak_ptr solve?

22Move Semantics

Read the lesson
Fill in the blankseasyMove Semantics

Complete the line so b takes over a's contents instead of copying them.

vector<int> b = std::(a);
Multiple choiceeasyMove Semantics

What happens to a vector after it's been moved from with the move constructor?

Multiple choicemediumMove Semantics

What does T&& mean as a parameter type?

Multiple choicemediumMove Semantics

Which adds an object by building it directly inside the vector?

Multiple choicehardMove Semantics

Why mark a move constructor noexcept?

23Templates

Read the lesson
Fill in the blankseasyTemplates

Complete the line that starts a function template.

 < T>
T twice(T x) { return x + x; }
Predict the outputeasyTemplates

What does this print?

template <typename T>
T twice(T x) { return x + x; }
// in main:
cout << twice(4) << " " << twice(string("ab"));
Multiple choicemediumTemplates

What happens when you call a function template with a new type?

Predict the outputmediumTemplates

What does this print?

template <typename T>
class Box {
    T v;
public:
    Box(T x) : v(x) {}
    T get() const { return v; }
};
// in main:
Box<double> b(7);
cout << b.get() / 2;
Multiple choicehardTemplates

Why are templates usually defined in header files?

24optional & variant

Read the lesson
Fill in the blankseasyoptional & variant

Complete the line so the function returns "no value".

optional<int> find(int id) {
    return ;
}
Multiple choiceeasyoptional & variant

What does optional<string> represent?

Predict the outputmediumoptional & variant

What does this print?

optional<int> a;
optional<int> b = 7;
cout << a.value_or(1) + b.value_or(1) << endl;
Multiple choicemediumoptional & variant

Which safely reads a string from variant<int, string> v without throwing?

Multiple choicehardoptional & variant

When is optional a better choice than an exception?

25Threads & Concurrency

Read the lesson
Fill in the blankseasyThreads & Concurrency

Complete the code so main waits for the thread to finish.

thread t(downloadFile);
t.();
Multiple choiceeasyThreads & Concurrency

When does a std::thread start running its function?

Multiple choicemediumThreads & Concurrency

What is a data race?

Multiple choicemediumThreads & Concurrency

What does lock_guard do?

Predict the outputhardThreads & Concurrency

Four threads each increment an atomic<int> 1,000 times. What's the final value?

26Scope and Linkage

Read the lesson
Multiple choicemediumScope and Linkage

The compiler sees a public function declaration, but the linker cannot find its definition. What should be checked?

27Const Correctness

Read the lesson
Multiple choicemediumConst Correctness

A cast removes const from an object originally declared const. What happens if code writes through the result?

28Casts and Numeric Safety

Read the lesson
Multiple choicemediumCasts and Numeric Safety

from_chars parses 12 from 12x without a conversion error. What additional check rejects this field?

29Array and Span

Read the lesson
Multiple choicemediumArray and Span

A runtime grid row must be exposed safely. Which sequence fits?

30String View Lifetimes

Read the lesson
Multiple choicemediumString View Lifetimes

A parsed code must remain valid after the input string is cleared. Which return type fits?

31Iterator Invalidation

Read the lesson
Multiple choicemediumIterator Invalidation

An order must be identified after a vector is filtered and extended. Which design is robust?

32List and Deque

Read the lesson
Multiple choicemediumList and Deque

A compatible-allocator list node is spliced into another list. What should the caller remember?

33Container Adaptors

Read the lesson
Multiple choicemediumContainer Adaptors

Two consumers share a queue. Which design prevents an empty-check race?

34Unordered Containers

Read the lesson
Multiple choicemediumUnordered Containers

A report must print unordered-map entries in alphabetic key order. Which design fits?

35Chrono and Dates

Read the lesson
Multiple choicemediumChrono and Dates

A deadline expires at equality. Which test set establishes that rule?

36Random Generation

Read the lesson
Multiple choicemediumRandom Generation

A selector needs three distinct IDs from a unique bounded list. Which approach has a clear termination argument?

37Friend Access

Read the lesson
Multiple choicemediumFriend Access

A friend reservation operation rejects insufficient stock. What should its test verify?

38Multiple Inheritance

Read the lesson
Multiple choicemediumMultiple Inheritance

An invoice contains an address but is not substitutable for an address. Which relationship is usually clearer?

39Special Members and Guarantees

Read the lesson
Multiple choicemediumSpecial Members and Guarantees

Which step makes the worked update's commit argument sound?

40Advanced Templates

Read the lesson
Multiple choicemediumAdvanced Templates

The field writer only observes arguments. Which parameter contract is appropriate?

41Concepts and Requires

Read the lesson
Multiple choicemediumConcepts and Requires

A type satisfies Reservable but returns true after subtracting too much stock. What follows?

42Ranges and Views

Read the lesson
Multiple choicemediumRanges and Views

A predicate captures threshold by value, then the original variable changes. What happens?

43Debugging and Testing

Read the lesson
Multiple choicemediumDebugging and Testing

A sanitizer build cannot link its runtime on the current platform. What should the report say?

44CMake and Builds

Read the lesson
Multiple choicemediumCMake and Builds

A new CTest executable links successfully. What establishes that its checks pass?

Next steps