C++C++

C++ exercises with solutions

Solve in editor

Write your solution right in the browser.

Open exercises with editor

1. Even numbers Beginner

Print all even numbers from 1 to 10 – each on its own line.

Expected output: 2 ⏎ 4 ⏎ 6 ⏎ 8 ⏎ 10

Note

Count in steps of two (i += 2) or check with i % 2 == 0.

Show sample solution
#include <iostream>

int main() {
    for (int i = 2; i <= 10; i += 2)
        std::cout << i << '\n';
}

2. FizzBuzz (1–15) Beginner

Print the numbers 1 to 15. For multiples of 3 print Fizz instead, for multiples of 5 print Buzz, and for both print FizzBuzz.

Expected output: 1 ⏎ 2 ⏎ Fizz ⏎ 4 ⏎ Buzz ⏎ Fizz ⏎ 7 ⏎ 8 ⏎ Fizz ⏎ Buzz ⏎ 11 ⏎ Fizz ⏎ 13 ⏎ 14 ⏎ FizzBuzz

Note

Check the case "divisible by 15" first, then 3 and 5.

Show sample solution
#include <iostream>

int main() {
    for (int i = 1; i <= 15; ++i) {
        if (i % 15 == 0)      std::cout << "FizzBuzz\n";
        else if (i % 3 == 0)  std::cout << "Fizz\n";
        else if (i % 5 == 0)  std::cout << "Buzz\n";
        else                  std::cout << i << '\n';
    }
}

3. Reverse a word Beginner

Reverse the string "Python" and print it.

Expected output: nohtyP

Note

std::reverse(wort.begin(), wort.end()) from <algorithm> reverses in place.

Show sample solution
#include <algorithm>
#include <iostream>
#include <string>

int main() {
    std::string wort = "Python";
    std::reverse(wort.begin(), wort.end());
    std::cout << wort << '\n';
}

4. Sum of squares Beginner

Compute the sum of the squares of the numbers 1 to 10 and print it.

Expected output: 385

Note

A loop from 1 to 10 and summe += i * i;.

Show sample solution
#include <iostream>

int main() {
    int summe = 0;
    for (int i = 1; i <= 10; ++i)
        summe += i * i;
    std::cout << summe << '\n';
}

5. Palindrome function Intermediate

Write a function bool ist_palindrom(std::string text) that returns true if the text reads the same forwards and backwards (ignoring case). Print ist_palindrom("Anna") and ist_palindrom("Python") (as true/false).

Expected output: true ⏎ false

Note

Convert everything to lowercase with std::transform and std::tolower. Compare the first half with the reverse view (text.rbegin()) using std::equal.

Show sample solution
#include <algorithm>
#include <cctype>
#include <iostream>
#include <string>

bool ist_palindrom(std::string text) {
    std::transform(text.begin(), text.end(), text.begin(),
                   [](unsigned char c) { return static_cast<char>(std::tolower(c)); });
    return std::equal(text.begin(), text.begin() + text.size() / 2, text.rbegin());
}

int main() {
    std::cout << std::boolalpha;
    std::cout << ist_palindrom("Anna") << '\n';
    std::cout << ist_palindrom("Python") << '\n';
}

6. Most frequent word Intermediate

Find the most frequent word in "a b a c b a" and print it.

Expected output: a

Note

Count with std::map<std::string, int> (++zaehler[wort]) and afterwards look for the pair with the largest value.

Show sample solution
#include <iostream>
#include <map>
#include <sstream>
#include <string>

int main() {
    std::istringstream text("a b a c b a");
    std::map<std::string, int> zaehler;
    std::string wort;
    while (text >> wort) ++zaehler[wort];

    std::string bestes;
    int maximum = 0;
    for (const auto& [w, n] : zaehler) {
        if (n > maximum) { maximum = n; bestes = w; }
    }
    std::cout << bestes << '\n';
}

7. Primes up to 30 Intermediate

Print all primes up to 30 on one line, separated by spaces (no trailing space).

Expected output: 2 3 5 7 11 13 17 19 23 29

Note

A number n ≥ 2 is prime if no divisor d with d * d <= n divides it without a remainder. Remember whether something has already been printed in order to control the spaces.

Show sample solution
#include <iostream>

bool ist_prim(int n) {
    if (n < 2) return false;
    for (int d = 2; d * d <= n; ++d)
        if (n % d == 0) return false;
    return true;
}

int main() {
    bool erste = true;
    for (int n = 2; n <= 30; ++n) {
        if (!ist_prim(n)) continue;
        if (!erste) std::cout << ' ';
        std::cout << n;
        erste = false;
    }
    std::cout << '\n';
}

8. Shapes with polymorphism Intermediate

Define an abstract class Form with the pure virtual method double flaeche() const. Derive Rechteck(breite, hoehe) and Quadrat(seite). Put a 3x4 rectangle and a square with side 2 into a std::vector<std::unique_ptr<Form>> and print each area on its own line.

Expected output: 12 ⏎ 4

Note

The base class needs a virtual destructor. Quadrat can inherit from Rechteck and call Rechteck(seite, seite) in its constructor. Create objects with std::make_unique.

Show sample solution
#include <iostream>
#include <memory>
#include <vector>

class Form {
public:
    virtual ~Form() = default;
    virtual double flaeche() const = 0;
};

class Rechteck : public Form {
public:
    Rechteck(double b, double h) : b_(b), h_(h) {}
    double flaeche() const override { return b_ * h_; }
private:
    double b_, h_;
};

class Quadrat : public Rechteck {
public:
    explicit Quadrat(double seite) : Rechteck(seite, seite) {}
};

int main() {
    std::vector<std::unique_ptr<Form>> formen;
    formen.push_back(std::make_unique<Rechteck>(3, 4));
    formen.push_back(std::make_unique<Quadrat>(2));
    for (const auto& f : formen)
        std::cout << f->flaeche() << '\n';
}

9. Generic stack Advanced

Write a class template Stapel<T> with push, pop (returns the top element and removes it) and leer(). Push 1, 2, 3 onto a Stapel<int> and print the values while clearing it (one per line).

Expected output: 3 ⏎ 2 ⏎ 1

Note

A std::vector<T> is enough internally: push_back, back() and pop_back(). Write pop so that you store the value temporarily before pop_back.

Show sample solution
#include <iostream>
#include <utility>
#include <vector>

template <typename T>
class Stapel {
public:
    void push(T wert) { daten_.push_back(std::move(wert)); }
    T pop() {
        T oben = std::move(daten_.back());
        daten_.pop_back();
        return oben;
    }
    bool leer() const { return daten_.empty(); }
private:
    std::vector<T> daten_;
};

int main() {
    Stapel<int> s;
    s.push(1);
    s.push(2);
    s.push(3);
    while (!s.leer())
        std::cout << s.pop() << '\n';
}

10. Ranges: squares of even numbers Advanced

Use a C++20 ranges pipeline (views::iota, filter, transform) to print the squares of all even numbers from 1 to 10 on one line, separated by spaces (no trailing space).

Expected output: 4 16 36 64 100

Note

std::views::iota(1, 11) generates 1..10. Chain first filter, then transform with |. For the separator, remember whether it is the first element.

Show sample solution
#include <iostream>
#include <ranges>

int main() {
    auto r = std::views::iota(1, 11)
           | std::views::filter([](int x) { return x % 2 == 0; })
           | std::views::transform([](int x) { return x * x; });
    bool erste = true;
    for (int x : r) {
        if (!erste) std::cout << ' ';
        std::cout << x;
        erste = false;
    }
    std::cout << '\n';
}