C++ course
cpp programming language icon

C++ Exercises: 22 Practice Problems with Solutions

C++ gives you C's control plus the standard library. These problems cover I/O, vectors, maps and sets, algorithms, references, templates, classes, virtual functions, operator overloading and smart pointers.

Each solution is a complete program with the includes it needs. Run it in the editor below and add stdin values in the Input box where a problem asks for them.

Run your answer here

Type your solution, press Run, and use the Input box when a problem asks you to read from standard input.

C++ Compiler
Output
Code runs on the Play with Coding execution engine — your code is saved locally for next time.

How to practise so it actually sticks

Attempt the problem before opening the solution, even if your first version is clumsy. A working ugly answer teaches more than a beautiful one you read. When you get stuck for more than five minutes, read the hint — not the solution — and try again.

After you pass, open the solution and ask what is different about it. Shorter? Fewer variables? A built-in you did not know? That comparison is where most of the growth happens. Then change the problem slightly: sort the other direction, handle an empty input, read a value instead of hard-coding it.

Aim for three to five problems a day rather than thirty in one sitting. Spacing practice over days is what moves syntax from "I can look it up" to "my fingers know it".

The exercises

Showing 22 of 22 exercises.

  1. BeginnerBasics & output

    1. Print a greeting

    Store "Ada" in a std::string and print "Hello, Ada!".

    Hint: cout << with the << operator chained.

    #include <iostream>
    #include <string>
    using namespace std;
    
    int main() {
        string name = ;
        return 0;
    }
    Show solution
    #include <iostream>
    #include <string>
    using namespace std;
    
    int main() {
        string name = "Ada";
        cout << "Hello, " << name << "!" << endl;
        return 0;
    }
  2. BeginnerBasics & output

    2. Read two numbers

    Read two integers from input and print their sum. Put two numbers in the Input box.

    Hint: cin >> a >> b;

    #include <iostream>
    using namespace std;
    
    int main() {
        int a, b;
        return 0;
    }
    Show solution
    #include <iostream>
    using namespace std;
    
    int main() {
        int a, b;
        cin >> a >> b;
        cout << a + b << endl;
        return 0;
    }
  3. BeginnerBasics & output

    3. auto and range-for

    Loop over a vector of three doubles with a range-based for loop and print each.

    Hint: for (auto v : values).

    #include <iostream>
    #include <vector>
    using namespace std;
    
    int main() {
        
        return 0;
    }
    Show solution
    #include <iostream>
    #include <vector>
    using namespace std;
    
    int main() {
        vector<double> values = {1.5, 2.5, 3.5};
        for (auto v : values) cout << v << " ";
        cout << endl;
        return 0;
    }
  4. BeginnerConditionals

    4. Even or odd

    Print "even" or "odd" for 17.

    Hint: Ternary or if/else, both fine.

    #include <iostream>
    using namespace std;
    
    int main() {
        int n = 17;
        return 0;
    }
    Show solution
    #include <iostream>
    using namespace std;
    
    int main() {
        int n = 17;
        cout << (n % 2 == 0 ? "even" : "odd") << endl;
        return 0;
    }
  5. BeginnerConditionals

    5. Grade from a score

    Print A for 90+, B for 80+, C for 70+, else F. Test with 84.

    Hint: Order the branches from highest to lowest.

    #include <iostream>
    using namespace std;
    
    int main() {
        int score = 84;
        return 0;
    }
    Show solution
    #include <iostream>
    using namespace std;
    
    int main() {
        int score = 84;
        if (score >= 90) cout << "A";
        else if (score >= 80) cout << "B";
        else if (score >= 70) cout << "C";
        else cout << "F";
        cout << endl;
        return 0;
    }
  6. BeginnerLoops

    6. FizzBuzz to 20

    Print 1..20, replacing multiples of 3 with "Fizz", 5 with "Buzz", both with "FizzBuzz".

    Hint: Handle the multiple of 15 first.

    #include <iostream>
    using namespace std;
    
    int main() {
        for (int i = 1; i <= 20; i++) {
        }
        return 0;
    }
    Show solution
    #include <iostream>
    using namespace std;
    
    int main() {
        for (int i = 1; i <= 20; 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";
        }
        return 0;
    }
  7. BeginnerLoops

    7. Star triangle

    Print a right-angled triangle of five rows of stars.

    Hint: std::string(i, '*') builds a row in one step.

    #include <iostream>
    #include <string>
    using namespace std;
    
    int main() {
        
        return 0;
    }
    Show solution
    #include <iostream>
    #include <string>
    using namespace std;
    
    int main() {
        for (int i = 1; i <= 5; i++) cout << string(i, '*') << "\n";
        return 0;
    }
  8. BeginnerVectors & STL

    8. Vector statistics

    For {4, 9, 1, 7, 3} print the sum, the largest and the smallest using the STL.

    Hint: accumulate from <numeric>, max_element and min_element from <algorithm>.

    #include <iostream>
    #include <vector>
    #include <numeric>
    #include <algorithm>
    using namespace std;
    
    int main() {
        vector<int> v = {4, 9, 1, 7, 3};
        return 0;
    }
    Show solution
    #include <iostream>
    #include <vector>
    #include <numeric>
    #include <algorithm>
    using namespace std;
    
    int main() {
        vector<int> v = {4, 9, 1, 7, 3};
        cout << accumulate(v.begin(), v.end(), 0) << " "
             << *max_element(v.begin(), v.end()) << " "
             << *min_element(v.begin(), v.end()) << endl;
        return 0;
    }
  9. IntermediateVectors & STL

    9. Sort with a custom comparator

    Sort {5, 2, 9, 1, 7} in descending order using std::sort and a lambda.

    Hint: sort(v.begin(), v.end(), [](int a, int b){ return a > b; }).

    #include <iostream>
    #include <vector>
    #include <algorithm>
    using namespace std;
    
    int main() {
        vector<int> v = {5, 2, 9, 1, 7};
        return 0;
    }
    Show solution
    #include <iostream>
    #include <vector>
    #include <algorithm>
    using namespace std;
    
    int main() {
        vector<int> v = {5, 2, 9, 1, 7};
        sort(v.begin(), v.end(), [](int a, int b) { return a > b; });
        for (int n : v) cout << n << " ";
        cout << endl;
        return 0;
    }
  10. IntermediateVectors & STL

    10. Count words with a map

    Count how often each word appears in "to be or not to be".

    Hint: map<string,int> counts; counts[word]++ starts at zero automatically.

    #include <iostream>
    #include <map>
    #include <sstream>
    #include <string>
    using namespace std;
    
    int main() {
        
        return 0;
    }
    Show solution
    #include <iostream>
    #include <map>
    #include <sstream>
    #include <string>
    using namespace std;
    
    int main() {
        string text = "to be or not to be", word;
        map<string, int> counts;
        istringstream in(text);
        while (in >> word) counts[word]++;
        for (auto &p : counts) cout << p.first << "=" << p.second << " ";
        cout << endl;
        return 0;
    }
  11. IntermediateVectors & STL

    11. Remove duplicates with a set

    Print the unique values of {3,1,3,7,1,9} in ascending order.

    Hint: std::set stores each key once and keeps them sorted.

    #include <iostream>
    #include <set>
    using namespace std;
    
    int main() {
        
        return 0;
    }
    Show solution
    #include <iostream>
    #include <set>
    using namespace std;
    
    int main() {
        set<int> s = {3, 1, 3, 7, 1, 9};
        for (int n : s) cout << n << " ";
        cout << endl;
        return 0;
    }
  12. BeginnerStrings

    12. Reverse a string

    Reverse "cplusplus" and print it.

    Hint: std::reverse works on any pair of iterators.

    #include <iostream>
    #include <string>
    #include <algorithm>
    using namespace std;
    
    int main() {
        string s = "cplusplus";
        return 0;
    }
    Show solution
    #include <iostream>
    #include <string>
    #include <algorithm>
    using namespace std;
    
    int main() {
        string s = "cplusplus";
        reverse(s.begin(), s.end());
        cout << s << endl;
        return 0;
    }
  13. IntermediateStrings

    13. Palindrome check

    Check whether "Never odd or even" is a palindrome, ignoring case and spaces.

    Hint: Build a cleaned lowercase copy first with isalnum and tolower.

    #include <iostream>
    #include <string>
    #include <algorithm>
    #include <cctype>
    using namespace std;
    
    int main() {
        
        return 0;
    }
    Show solution
    #include <iostream>
    #include <string>
    #include <algorithm>
    #include <cctype>
    using namespace std;
    
    int main() {
        string s = "Never odd or even", t;
        for (char c : s) if (isalnum((unsigned char)c)) t += tolower(c);
        string r = t;
        reverse(r.begin(), r.end());
        cout << (t == r ? "yes" : "no") << endl;
        return 0;
    }
  14. IntermediateFunctions

    14. Reference parameters

    Write swap_values(int &a, int &b) and swap two variables in main.

    Hint: References avoid pointer syntax entirely.

    #include <iostream>
    using namespace std;
    
    int main() {
        int x = 3, y = 8;
        return 0;
    }
    Show solution
    #include <iostream>
    using namespace std;
    
    void swap_values(int &a, int &b) {
        int t = a; a = b; b = t;
    }
    
    int main() {
        int x = 3, y = 8;
        swap_values(x, y);
        cout << x << " " << y << endl;
        return 0;
    }
  15. AdvancedFunctions

    15. A function template

    Write a template maxOf(a, b) and call it with ints and with doubles.

    Hint: template <typename T> before the function.

    #include <iostream>
    using namespace std;
    
    int main() {
        return 0;
    }
    Show solution
    #include <iostream>
    using namespace std;
    
    template <typename T>
    T maxOf(T a, T b) { return a > b ? a : b; }
    
    int main() {
        cout << maxOf(3, 9) << " " << maxOf(2.5, 1.5) << endl;
        return 0;
    }
  16. IntermediateClasses & OOP

    16. A class with encapsulation

    Write a BankAccount class with a private balance, deposit, withdraw and a getter.

    Hint: Refuse withdrawals bigger than the balance.

    Show solution
    #include <iostream>
    #include <stdexcept>
    using namespace std;
    
    class BankAccount {
        double balance = 0;
    public:
        void deposit(double n) { balance += n; }
        void withdraw(double n) {
            if (n > balance) throw runtime_error("Insufficient funds");
            balance -= n;
        }
        double getBalance() const { return balance; }
    };
    
    int main() {
        BankAccount acc;
        acc.deposit(100);
        acc.withdraw(30);
        cout << acc.getBalance() << endl;
        return 0;
    }
  17. AdvancedClasses & OOP

    17. Virtual functions

    Write an abstract Shape with a virtual area(), then Square and Circle, and print both areas through base pointers.

    Hint: Declare the base method virtual and give the base a virtual destructor.

    Show solution
    #include <iostream>
    #include <vector>
    #include <memory>
    #include <cmath>
    using namespace std;
    
    class Shape {
    public:
        virtual double area() const = 0;
        virtual ~Shape() = default;
    };
    class Square : public Shape {
        double side;
    public:
        Square(double s) : side(s) {}
        double area() const override { return side * side; }
    };
    class Circle : public Shape {
        double r;
    public:
        Circle(double r) : r(r) {}
        double area() const override { return M_PI * r * r; }
    };
    
    int main() {
        vector<unique_ptr<Shape>> shapes;
        shapes.push_back(make_unique<Square>(3));
        shapes.push_back(make_unique<Circle>(1));
        for (auto &s : shapes) cout << s->area() << " ";
        cout << endl;
        return 0;
    }
  18. AdvancedClasses & OOP

    18. Overload an operator

    Write a Vec2 struct with operator+ and print the sum of two vectors.

    Hint: Return a new Vec2 from the operator.

    Show solution
    #include <iostream>
    using namespace std;
    
    struct Vec2 {
        double x, y;
        Vec2 operator+(const Vec2 &o) const { return {x + o.x, y + o.y}; }
    };
    
    int main() {
        Vec2 a{1, 2}, b{3, 4};
        Vec2 c = a + b;
        cout << c.x << "," << c.y << endl;
        return 0;
    }
  19. IntermediateExceptions

    19. Throw and catch

    Throw std::invalid_argument for a negative age and catch it, printing the message.

    Hint: catch (const exception &e) and use e.what().

    #include <iostream>
    #include <stdexcept>
    using namespace std;
    
    int main() {
        
        return 0;
    }
    Show solution
    #include <iostream>
    #include <stdexcept>
    using namespace std;
    
    int main() {
        try {
            int age = -5;
            if (age < 0) throw invalid_argument("age cannot be negative");
        } catch (const exception &e) {
            cout << "Rejected: " << e.what() << endl;
        }
        return 0;
    }
  20. AdvancedMemory

    20. Use a smart pointer

    Create a unique_ptr to an int, change its value and print it — no delete needed.

    Hint: make_unique<int>(5) then *p.

    #include <iostream>
    #include <memory>
    using namespace std;
    
    int main() {
        
        return 0;
    }
    Show solution
    #include <iostream>
    #include <memory>
    using namespace std;
    
    int main() {
        auto p = make_unique<int>(5);
        *p += 10;
        cout << *p << endl;
        return 0;
    }
  21. AdvancedAlgorithms

    21. Binary search

    Implement binary search over a sorted vector and print the index of 9, or -1.

    Hint: Track lo and hi and compare the middle element.

    #include <iostream>
    #include <vector>
    using namespace std;
    
    int main() {
        vector<int> v = {1, 3, 5, 7, 9, 11};
        return 0;
    }
    Show solution
    #include <iostream>
    #include <vector>
    using namespace std;
    
    int main() {
        vector<int> v = {1, 3, 5, 7, 9, 11};
        int target = 9, lo = 0, hi = v.size() - 1, found = -1;
        while (lo <= hi) {
            int mid = (lo + hi) / 2;
            if (v[mid] == target) { found = mid; break; }
            if (v[mid] < target) lo = mid + 1; else hi = mid - 1;
        }
        cout << found << endl;
        return 0;
    }
  22. AdvancedAlgorithms

    22. Sieve of Eratosthenes

    Print all primes below 50 using a sieve.

    Hint: Mark multiples of each prime as composite in a bool vector.

    #include <iostream>
    #include <vector>
    using namespace std;
    
    int main() {
        
        return 0;
    }
    Show solution
    #include <iostream>
    #include <vector>
    using namespace std;
    
    int main() {
        int n = 50;
        vector<bool> composite(n, false);
        for (int p = 2; p * p < n; p++)
            if (!composite[p])
                for (int m = p * p; m < n; m += p) composite[m] = true;
        for (int i = 2; i < n; i++) if (!composite[i]) cout << i << " ";
        cout << endl;
        return 0;
    }

What to do next

If a whole topic feels shaky, go back to that chapter in the 17-chapter C++ course and re-read it, then return here. When the advanced problems feel routine, take the final C++ quiz and claim your certificate, or open the C++ online compiler and build something of your own.