C++ Programs

Practice Code Examples

Hands-on C++ programs to practice and master the language. From basic to advanced level.

C++20 ✓ Practice 40 Programs
01

Basic Programs

#1Check Prime NumberBasic
C++
#include <cmath>
bool isPrime(int n) {
    if (n < 2) return false;
    for (int i = 2; i <= std::sqrt(n); i++)
        if (n % i == 0) return false;
    return true;
}
isPrime(17);   // true
#2Factorial (Recursive)Basic
C++
long factorial(int n) {
    return n <= 1 ? 1 : n * factorial(n - 1);
}
factorial(5);   // 120
#3Fibonacci SequenceBasic
C++
int a = 0, b = 1;
for (int i = 0; i < 8; i++) {
    std::cout << a << ' ';   // 0 1 1 2 3 5 8 13
    int next = a + b; a = b; b = next;
}
#4Reverse a StringBasic
C++
#include <algorithm>
std::string s = "hello";
std::reverse(s.begin(), s.end());   // "olleh"
#5Check PalindromeBasic
C++
#include <algorithm>
bool isPalindrome(std::string s) {
    std::string r = s;
    std::reverse(r.begin(), r.end());
    return s == r;
}
isPalindrome("racecar");   // true
#6Swap Two VariablesBasic
C++
int a = 5, b = 10;
std::swap(a, b);   // a=10, b=5 — STL swap
#7Celsius to FahrenheitBasic
C++
double toFahrenheit(double c) { return c * 9 / 5 + 32; }
toFahrenheit(100);   // 212
#8Check Odd or EvenBasic
C++
bool isEven(int n) { return n % 2 == 0; }
isEven(7);   // false
#9Check Leap YearBasic
C++
bool isLeap(int y) {
    return (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
}
isLeap(2024);   // true
#10Sum of Natural NumbersBasic
C++
int sumUpTo(int n) { return n * (n + 1) / 2; }
sumUpTo(100);   // 5050
#11GCD (Euclid) and LCMBasic
C++
int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); }
int lcm(int a, int b) { return a / gcd(a, b) * b; }
gcd(36, 60);   // 12
#12Multiplication TableBasic
C++
int n = 5;
for (int i = 1; i <= 10; i++)
    std::cout << n << " x " << i << " = " << n * i << '\n';
#13Sum of DigitsBasic
C++
int digitSum(int n) {
    int sum = 0;
    while (n > 0) { sum += n % 10; n /= 10; }
    return sum;
}
digitSum(1234);   // 10
#14Power (fast exponentiation)Basic
C++
long power(int base, int exp) {
    long r = 1;
    while (exp > 0) {
        if (exp & 1) r *= base;
        base *= base; exp >>= 1;
    }
    return r;
}
power(2, 10);   // 1024
#15Count VowelsBasic
C++
int countVowels(std::string s) {
    int c = 0;
    for (char ch : s)
        if (std::string("aeiouAEIOU").find(ch) != std::string::npos) c++;
    return c;
}
countVowels("CppLang");   // 1
#16Largest of ThreeBasic
C++
#include <algorithm>
int largest = std::max({4, 19, 7});   // 19 (initializer_list max)
#17Decimal to BinaryBasic
C++
#include <bitset>
std::string bin = std::bitset<8>(42).to_string();   // "00101010"
#18FizzBuzzBasic
C++
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';
}
#19Read Numbers into a vectorBasic
C++
#include <vector>
int n; std::cin >> n;
std::vector<int> v(n);
for (auto& x : v) std::cin >> x;   // read n numbers
#20Armstrong NumberBasic
C++
bool isArmstrong(int n) {
    int sum = 0, t = n;
    while (t) { int d = t % 10; sum += d * d * d; t /= 10; }
    return sum == n;
}
isArmstrong(153);   // true
02

Intermediate Programs

#21Binary SearchIntermediate
C++
int binarySearch(std::vector<int>& a, int target) {
    int lo = 0, hi = a.size() - 1;
    while (lo <= hi) {
        int mid = lo + (hi - lo) / 2;
        if (a[mid] == target) return mid;
        if (a[mid] < target) lo = mid + 1; else hi = mid - 1;
    }
    return -1;
}
#22Bubble SortIntermediate
C++
void bubbleSort(std::vector<int>& a) {
    for (size_t i = 0; i < a.size(); i++)
        for (size_t j = 0; j + i + 1 < a.size(); j++)
            if (a[j] > a[j + 1]) std::swap(a[j], a[j + 1]);
}
#23Count Word FrequencyIntermediate
C++
#include <unordered_map>
#include <sstream>
std::unordered_map<std::string, int> freq;
std::istringstream iss("the cat and the dog");
std::string w;
while (iss >> w) freq[w]++;   // {the:2, cat:1, and:1, dog:1}
#24Sum & Max of a vectorIntermediate
C++
#include <numeric>
#include <algorithm>
std::vector<int> v = {4, 9, 2, 7};
int sum = std::accumulate(v.begin(), v.end(), 0);   // 22
int mx = *std::max_element(v.begin(), v.end());   // 9
#25Reverse an IntegerIntermediate
C++
int reverse(int n) {
    int r = 0;
    while (n) { r = r * 10 + n % 10; n /= 10; }
    return r;
}
reverse(1234);   // 4321
#26Remove Duplicates (set)Intermediate
C++
#include <set>
std::vector<int> v = {1, 2, 2, 3, 3, 4};
std::set<int> s(v.begin(), v.end());   // {1,2,3,4}
#27Second LargestIntermediate
C++
#include <set>
std::set<int, std::greater<>> s = {5, 9, 9, 3};   // {9,5,3}
auto it = ++s.begin();
int second = *it;   // 5
#28Check AnagramIntermediate
C++
#include <algorithm>
bool isAnagram(std::string a, std::string b) {
    std::sort(a.begin(), a.end());
    std::sort(b.begin(), b.end());
    return a == b;
}
isAnagram("listen", "silent");   // true
#29Rotate a vector by KIntermediate
C++
#include <algorithm>
std::vector<int> v = {1, 2, 3, 4, 5};
int k = 2;
std::rotate(v.begin(), v.begin() + k, v.end());   // {3,4,5,1,2}
#30Two Sum (unordered_map)Intermediate
C++
#include <unordered_map>
std::vector<int> twoSum(std::vector<int>& a, int target) {
    std::unordered_map<int, int> seen;
    for (int i = 0; i < (int)a.size(); i++) {
        int need = target - a[i];
        if (seen.count(need)) return {seen[need], i};
        seen[a[i]] = i;
    }
    return {};
}
#31Find Missing NumberIntermediate
C++
#include <numeric>
int missing(std::vector<int>& a, int n) {
    int expected = n * (n + 1) / 2;
    return expected - std::accumulate(a.begin(), a.end(), 0);
}
#32Merge Two Sorted vectorsIntermediate
C++
#include <algorithm>
std::vector<int> a = {1, 3, 5}, b = {2, 4, 6}, r(6);
std::merge(a.begin(), a.end(), b.begin(), b.end(), r.begin());
// r = {1,2,3,4,5,6}
#33Title-Case a SentenceIntermediate
C++
#include <cctype>
std::string s = "the quick fox";
bool newWord = true;
for (char& c : s) {
    if (newWord && std::isalpha(c)) c = std::toupper(c);
    newWord = (c == ' ');
}   // "The Quick Fox"
#34Sort by Custom ComparatorIntermediate
C++
#include <algorithm>
std::vector<std::string> words = {"bb", "a", "ccc"};
std::sort(words.begin(), words.end(),
    [](const auto& x, const auto& y){ return x.size() < y.size(); });
// {"a", "bb", "ccc"}
#35Fibonacci with MemoizationIntermediate
C++
#include <unordered_map>
std::unordered_map<int, long> memo;
long fib(int n) {
    if (n <= 1) return n;
    if (memo.count(n)) return memo[n];
    return memo[n] = fib(n - 1) + fib(n - 2);
}
03

Advanced Programs

#36Merge SortAdvanced
C++
void mergeSort(std::vector<int>& a, int lo, int hi) {
    if (lo >= hi) return;
    int mid = lo + (hi - lo) / 2;
    mergeSort(a, lo, mid);
    mergeSort(a, mid + 1, hi);
    std::vector<int> tmp;
    int i = lo, j = mid + 1;
    while (i <= mid && j <= hi) tmp.push_back(a[i] <= a[j] ? a[i++] : a[j++]);
    while (i <= mid) tmp.push_back(a[i++]);
    while (j <= hi) tmp.push_back(a[j++]);
    std::copy(tmp.begin(), tmp.end(), a.begin() + lo);
}
#37Quick SortAdvanced
C++
void quickSort(std::vector<int>& a, int lo, int hi) {
    if (lo >= hi) return;
    int pivot = a[hi], i = lo - 1;
    for (int j = lo; j < hi; j++)
        if (a[j] < pivot) std::swap(a[++i], a[j]);
    std::swap(a[i + 1], a[hi]);
    quickSort(a, lo, i);
    quickSort(a, i + 2, hi);
}
#38Generic Stack (Template)Advanced
C++
template<typename T>
class Stack {
    std::vector<T> data;
public:
    void push(const T& x) { data.push_back(x); }
    T pop() { T t = data.back(); data.pop_back(); return t; }
    bool empty() const { return data.empty(); }
};
#39Bank Account (RAII / OOP)Advanced
C++
class Account {
    double balance = 0;
public:
    void deposit(double amt) {
        if (amt <= 0) throw std::invalid_argument("bad amount");
        balance += amt;
    }
    void withdraw(double amt) {
        if (amt > balance) throw std::runtime_error("insufficient");
        balance -= amt;
    }
    double getBalance() const { return balance; }
};
#40unique_ptr Linked ListAdvanced
C++
#include <memory>
struct Node {
    int value;
    std::unique_ptr<Node> next;   // owns the rest of the list
    Node(int v) : value(v), next(nullptr) {}
};

auto head = std::make_unique<Node>(1);
head->next = std::make_unique<Node>(2);
// entire list freed automatically when head goes out of scope