Feeling stuck knowing C++ syntax but unsure how to actually build something with it? That gap between watching tutorials and writing real code can be frustrating—but it disappears with practice. This post brings you 100 C++ practice problems with clear, step-by-step solutions designed to make your skills stick.
You’ll start with fundamentals like variables, loops, and functions, then confidently tackle pointers, classes, STL containers, inheritance, and memory management. Every problem is explained in plain, simple language—try the code yourself first, then check the solution and understand the why behind it.
Practice is key because programming is a hands-on skill; each problem you solve builds problem-solving muscle and makes complex concepts feel natural. Whether you’re a beginner diving into C++ or preparing for a technical interview, these exercises will help you feel capable and truly ready. Pick a problem, start coding, and enjoy that “I really got this!” moment.
Also try it: 100 Rust practice problems with solutions
1. Write a program that prints “Hello, World!” to the console.
cpp
#include <iostream>
int main() {
std::cout << "Hello, World!" << std::endl;
return 0;
}
2. Write a program that declares two integer variables, assigns them values, and prints their sum.
cpp
#include <iostream>
int main() {
int a = 10, b = 20;
std::cout << "Sum: " << a + b << std::endl;
return 0;
}
3. Write a program that takes an integer input from the user and prints whether it is even or odd.
cpp
#include <iostream>
int main() {
int num;
std::cout << "Enter a number: ";
std::cin >> num;
if (num % 2 == 0)
std::cout << num << " is even" << std::endl;
else
std::cout << num << " is odd" << std::endl;
return 0;
}
4. Write a program that prints the numbers from 1 to 10 using a for loop.
cpp
#include <iostream>
int main() {
for (int i = 1; i <= 10; i++)
std::cout << i << " ";
return 0;
}
5. Write a program that prints the factorial of a given number (e.g., 5).
cpp
#include <iostream>
int main() {
int n = 5, fact = 1;
for (int i = 1; i <= n; i++)
fact *= i;
std::cout << "Factorial of " << n << " is " << fact << std::endl;
return 0;
}
6. Write a program to reverse a string (e.g., “Hello” → “olleH”).
cpp
#include <iostream>
#include <string>
#include <algorithm>
int main() {
std::string str = "Hello";
std::reverse(str.begin(), str.end());
std::cout << str << std::endl;
return 0;
}
7. Write a program to check if a string is a palindrome (e.g., “radar”).
cpp
#include <iostream>
#include <string>
int main() {
std::string str = "radar";
bool isPal = true;
for (size_t i = 0; i < str.length() / 2; i++) {
if (str[i] != str[str.length() - 1 - i]) {
isPal = false;
break;
}
}
std::cout << (isPal ? "Palindrome" : "Not palindrome") << std::endl;
return 0;
}
8. Write a program to find the largest element in an array {3, 7, 1, 9, 4}.
cpp
#include <iostream>
int main() {
int arr[] = {3, 7, 1, 9, 4};
int max = arr[0];
for (int i = 1; i < 5; i++)
if (arr[i] > max) max = arr[i];
std::cout << "Largest: " << max << std::endl;
return 0;
}
9. Write a program to calculate the sum of all elements in an array {2,4,6,8}.
cpp
#include <iostream>
int main() {
int arr[] = {2,4,6,8};
int sum = 0;
for (int num : arr) sum += num;
std::cout << "Sum: " << sum << std::endl;
return 0;
}
10. Write a program that counts the number of vowels in a string “Hello World”.
cpp
#include <iostream>
#include <string>
int main() {
std::string str = "Hello World";
int count = 0;
for (char c : str) {
c = tolower(c);
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u')
count++;
}
std::cout << "Vowels: " << count << std::endl;
return 0;
}
11. Write a program that prints the Fibonacci series up to 10 terms.
cpp
#include <iostream>
int main() {
int n = 10, a = 0, b = 1;
std::cout << "Fibonacci: ";
for (int i = 0; i < n; i++) {
std::cout << a << " ";
int next = a + b;
a = b;
b = next;
}
return 0;
}
12. Write a program that checks if a given number is prime (e.g., 17).
cpp
#include <iostream>
#include <cmath>
int main() {
int num = 17;
bool isPrime = true;
if (num <= 1) isPrime = false;
else {
for (int i = 2; i <= sqrt(num); i++) {
if (num % i == 0) {
isPrime = false;
break;
}
}
}
std::cout << num << (isPrime ? " is prime" : " is not prime") << std::endl;
return 0;
}
13. Write a program to remove duplicate elements from an array {1,2,2,3,4,4,5} (using a set).
cpp
#include <iostream>
#include <set>
int main() {
int arr[] = {1,2,2,3,4,4,5};
std::set<int> s(arr, arr + 7);
for (int val : s) std::cout << val << " ";
return 0;
}
14. Write a program that sorts an array {5,2,8,1,3} in ascending order.
cpp
#include <iostream>
#include <algorithm>
int main() {
int arr[] = {5,2,8,1,3};
int n = sizeof(arr)/sizeof(arr[0]);
std::sort(arr, arr + n);
for (int x : arr) std::cout << x << " ";
return 0;
}
15. Write a program that finds the second largest number in an array {10,20,4,45,99}.
cpp
#include <iostream>
#include <algorithm>
int main() {
int arr[] = {10,20,4,45,99};
int n = sizeof(arr)/sizeof(arr[0]);
std::sort(arr, arr + n);
std::cout << "Second largest: " << arr[n-2] << std::endl;
return 0;
}
16. Write a function that returns the greatest common divisor (GCD) of two numbers.
cpp
#include <iostream>
int gcd(int a, int b) {
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
return a;
}
int main() {
std::cout << gcd(48, 18) << std::endl;
return 0;
}
17. Write a class Rectangle with fields length and width, a constructor, and a method to compute area.
cpp
#include <iostream>
class Rectangle {
double length, width;
public:
Rectangle(double l, double w) : length(l), width(w) {}
double area() { return length * width; }
};
int main() {
Rectangle r(5, 3);
std::cout << "Area: " << r.area() << std::endl;
return 0;
}
18. Write a program that demonstrates function overloading by creating two add functions (one for ints, one for doubles).
cpp
#include <iostream>
int add(int a, int b) { return a + b; }
double add(double a, double b) { return a + b; }
int main() {
std::cout << add(5, 10) << std::endl;
std::cout << add(2.5, 3.7) << std::endl;
return 0;
}
19. Write a program that creates a Student class with name and roll number, then prints the object’s details.
cpp
#include <iostream>
#include <string>
class Student {
std::string name;
int roll;
public:
Student(std::string n, int r) : name(n), roll(r) {}
void display() {
std::cout << "Name: " << name << ", Roll: " << roll << std::endl;
}
};
int main() {
Student s("Alice", 101);
s.display();
return 0;
}
20. Write a program that uses inheritance: a base class Animal with a virtual function sound(), and a derived class Dog that overrides it.
cpp
#include <iostream>
class Animal {
public:
virtual void sound() { std::cout << "Animal makes sound" << std::endl; }
};
class Dog : public Animal {
public:
void sound() override { std::cout << "Dog barks" << std::endl; }
};
int main() {
Animal* a = new Dog();
a->sound();
delete a;
return 0;
}
21. Write a program that uses an abstract class Drawable with a pure virtual function draw(), and a class Circle that implements it.
cpp
#include <iostream>
class Drawable {
public:
virtual void draw() = 0;
};
class Circle : public Drawable {
public:
void draw() override { std::cout << "Drawing Circle" << std::endl; }
};
int main() {
Circle c;
c.draw();
return 0;
}
22. Write a program that handles division by zero using try-catch.
cpp
#include <iostream>
int main() {
try {
int result = 10 / 0;
} catch (std::exception& e) {
std::cout << "Cannot divide by zero!" << std::endl;
}
return 0;
}
23. Write a program that reads a line from the user and prints its length.
cpp
#include <iostream>
#include <string>
int main() {
std::string line;
std::cout << "Enter a string: ";
std::getline(std::cin, line);
std::cout << "Length: " << line.length() << std::endl;
return 0;
}
24. Write a program that counts the number of words in a sentence using stringstream.
cpp
#include <iostream>
#include <sstream>
#include <string>
int main() {
std::string sentence = "The quick brown fox";
std::stringstream ss(sentence);
std::string word;
int count = 0;
while (ss >> word) count++;
std::cout << "Word count: " << count << std::endl;
return 0;
}
25. Write a program that converts a vector of strings to uppercase using loops.
cpp
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
int main() {
std::vector<std::string> words = {"apple", "banana", "cherry"};
for (auto& w : words) {
std::transform(w.begin(), w.end(), w.begin(), ::toupper);
std::cout << w << std::endl;
}
return 0;
}
26. Write a program that uses a vector to store 5 integers and then prints them.
cpp
#include <iostream>
#include <vector>
int main() {
std::vector<int> vec;
for (int i = 1; i <= 5; i++) vec.push_back(i);
for (int v : vec) std::cout << v << " ";
return 0;
}
27. Write a program that checks if a given string contains only digits.
cpp
#include <iostream>
#include <string>
#include <cctype>
int main() {
std::string str = "12345";
bool onlyDigits = true;
for (char c : str) {
if (!std::isdigit(c)) {
onlyDigits = false;
break;
}
}
std::cout << (onlyDigits ? "Only digits" : "Contains non-digits") << std::endl;
return 0;
}
28. Write a program that finds the common elements between two integer arrays.
cpp
#include <iostream>
#include <set>
int main() {
int arr1[] = {1,2,3,4};
int arr2[] = {3,4,5,6};
std::set<int> s(arr1, arr1+4);
for (int num : arr2) {
if (s.find(num) != s.end())
std::cout << num << " ";
}
return 0;
}
29. Write a program that squares each element of an array using a lambda.
cpp
#include <iostream>
#include <algorithm>
#include <vector>
int main() {
std::vector<int> v = {1,2,3,4};
std::transform(v.begin(), v.end(), v.begin(), [](int x) { return x * x; });
for (int x : v) std::cout << x << " ";
return 0;
}
30. Write a program that writes a string to a file named “output.txt” and then reads it back (using fstream).
cpp
#include <fstream>
#include <iostream>
#include <string>
int main() {
std::ofstream out("output.txt");
out << "Hello C++";
out.close();
std::ifstream in("output.txt");
std::string content;
std::getline(in, content);
std::cout << content << std::endl;
return 0;
}
31. Write a program that uses recursion to compute the factorial of a number.
cpp
#include <iostream>
int fact(int n) {
if (n <= 1) return 1;
return n * fact(n-1);
}
int main() {
std::cout << fact(5) << std::endl;
return 0;
}
32. Write a program that prints a multiplication table (1 to 10) for a given number.
cpp
#include <iostream>
int main() {
int n = 7;
for (int i = 1; i <= 10; i++)
std::cout << n << " x " << i << " = " << n*i << std::endl;
return 0;
}
33. Write a program that removes all whitespace from a string.
cpp
#include <iostream>
#include <string>
#include <algorithm>
int main() {
std::string str = " Hello World ";
str.erase(std::remove_if(str.begin(), str.end(), ::isspace), str.end());
std::cout << str << std::endl;
return 0;
}
34. Write a program that swaps two numbers without using a third variable.
cpp
#include <iostream>
int main() {
int a = 5, b = 10;
a = a + b;
b = a - b;
a = a - b;
std::cout << "a=" << a << ", b=" << b << std::endl;
return 0;
}
35. Write a program that creates a std::map to store name-age pairs and prints them.
cpp
#include <iostream>
#include <map>
#include <string>
int main() {
std::map<std::string, int> ages;
ages["Alice"] = 25;
ages["Bob"] = 30;
for (auto& p : ages)
std::cout << p.first << ": " << p.second << std::endl;
return 0;
}
36. Write a program that sorts a list of strings alphabetically.
cpp
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
int main() {
std::vector<std::string> words = {"banana", "apple", "cherry"};
std::sort(words.begin(), words.end());
for (auto& w : words) std::cout << w << " ";
return 0;
}
Also try it: 100 Java practice problems with solutions
37. Write a program that finds the first non-repeated character in a string “swiss”.
cpp
#include <iostream>
#include <unordered_map>
#include <string>
int main() {
std::string str = "swiss";
std::unordered_map<char, int> count;
for (char c : str) count[c]++;
for (char c : str) {
if (count[c] == 1) {
std::cout << c << std::endl;
break;
}
}
return 0;
}
38. Write a program that checks if two strings are anagrams (e.g., “listen” and “silent”).
cpp
#include <iostream>
#include <algorithm>
#include <string>
int main() {
std::string s1 = "listen", s2 = "silent";
std::sort(s1.begin(), s1.end());
std::sort(s2.begin(), s2.end());
std::cout << (s1 == s2 ? "Anagrams" : "Not anagrams") << std::endl;
return 0;
}
39. Write a program that implements a simple counter using a static variable inside a class.
cpp
#include <iostream>
class Counter {
static int count;
public:
Counter() { count++; }
static int getCount() { return count; }
};
int Counter::count = 0;
int main() {
Counter c1, c2;
std::cout << "Objects created: " << Counter::getCount() << std::endl;
return 0;
}
40. Write a program that uses std::chrono to measure the time taken by a loop.
cpp
#include <iostream>
#include <chrono>
int main() {
auto start = std::chrono::steady_clock::now();
for (int i = 0; i < 1000000; i++);
auto end = std::chrono::steady_clock::now();
auto diff = end - start;
std::cout << "Time: " << std::chrono::duration<double>(diff).count() << " s\n";
return 0;
}
41. Write a program that rotates an array to the left by k positions (k=2).
cpp
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> v = {1,2,3,4,5};
int k = 2;
std::rotate(v.begin(), v.begin() + k, v.end());
for (int x : v) std::cout << x << " ";
return 0;
}
42. Write a program that finds the missing number in an array of 1..n (e.g., {1,2,3,5} missing 4).
cpp
#include <iostream>
int main() {
int arr[] = {1,2,3,5};
int n = 5;
int total = n*(n+1)/2;
int sum = 0;
for (int x : arr) sum += x;
std::cout << "Missing: " << total - sum << std::endl;
return 0;
}
43. Write a program that counts the occurrences of each character in a string using std::map.
cpp
#include <iostream>
#include <map>
#include <string>
int main() {
std::string str = "abracadabra";
std::map<char, int> freq;
for (char c : str) freq[c]++;
for (auto& p : freq)
std::cout << p.first << ": " << p.second << std::endl;
return 0;
}
44. Write a program that merges two sorted arrays into one sorted array.
cpp
#include <iostream>
#include <vector>
int main() {
std::vector<int> a = {1,3,5};
std::vector<int> b = {2,4,6};
std::vector<int> merged;
size_t i=0, j=0;
while (i < a.size() && j < b.size()) {
if (a[i] < b[j]) merged.push_back(a[i++]);
else merged.push_back(b[j++]);
}
while (i < a.size()) merged.push_back(a[i++]);
while (j < b.size()) merged.push_back(b[j++]);
for (int x : merged) std::cout << x << " ";
return 0;
}
45. Write a program that uses std::sqrt from <cmath> to compute the square root of a number.
cpp
#include <iostream>
#include <cmath>
int main() {
double num = 25;
double result = std::sqrt(num);
std::cout << result << std::endl;
return 0;
}
46. Write a program that throws a custom exception when a negative number is passed to a function.
cpp
#include <iostream>
#include <stdexcept>
void checkPositive(int n) {
if (n < 0) throw std::invalid_argument("Negative number");
}
int main() {
try {
checkPositive(-5);
} catch (std::exception& e) {
std::cout << "Caught: " << e.what() << std::endl;
}
return 0;
}
47. Write a program that simulates a simple ATM with balance check and withdrawal.
cpp
#include <iostream>
class ATM {
double balance = 1000;
public:
void withdraw(double amount) {
if (amount <= balance) {
balance -= amount;
std::cout << "Withdrawn: " << amount << std::endl;
} else {
std::cout << "Insufficient balance" << std::endl;
}
}
double getBalance() { return balance; }
};
int main() {
ATM atm;
atm.withdraw(200);
std::cout << "Balance: " << atm.getBalance() << std::endl;
return 0;
}
48. Write a program that computes the power of a number using recursion (x^n).
cpp
#include <iostream>
int power(int base, int exp) {
if (exp == 0) return 1;
return base * power(base, exp - 1);
}
int main() {
std::cout << power(2, 5) << std::endl;
return 0;
}
49. Write a program that checks if a string is a valid palindrome considering only alphanumeric characters.
cpp
#include <iostream>
#include <string>
#include <cctype>
int main() {
std::string s = "A man, a plan, a canal: Panama";
std::string cleaned;
for (char c : s) {
if (std::isalnum(c)) cleaned += tolower(c);
}
std::string rev(cleaned.rbegin(), cleaned.rend());
std::cout << (cleaned == rev ? "Palindrome" : "Not palindrome") << std::endl;
return 0;
}
50. Write a program that creates a simple thread using std::thread.
cpp
#include <iostream>
#include <thread>
void hello() { std::cout << "Hello from thread" << std::endl; }
int main() {
std::thread t(hello);
t.join();
return 0;
}
51. Write a program that uses std::mutex to protect a shared counter from race conditions.
cpp
#include <iostream>
#include <thread>
#include <mutex>
#include <vector>
int counter = 0;
std::mutex mtx;
void increment() {
for (int i = 0; i < 1000; i++) {
std::lock_guard<std::mutex> lock(mtx);
counter++;
}
}
int main() {
std::thread t1(increment), t2(increment);
t1.join(); t2.join();
std::cout << counter << std::endl;
return 0;
}
52. Write a program that reads all lines from a text file and prints them.
cpp
#include <iostream>
#include <fstream>
#include <string>
int main() {
std::ifstream file("input.txt");
std::string line;
while (getline(file, line))
std::cout << line << std::endl;
return 0;
}
53. Write a program that writes a vector of strings to a file using std::ofstream.
cpp
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
int main() {
std::vector<std::string> lines = {"Hello", "World"};
std::ofstream out("output.txt");
for (const auto& line : lines) out << line << std::endl;
return 0;
}
54. Write a program that sorts a std::map by values (by copying to a vector of pairs).
cpp
#include <iostream>
#include <map>
#include <vector>
#include <algorithm>
int main() {
std::map<std::string, int> m = {{"A",3}, {"B",1}, {"C",2}};
std::vector<std::pair<std::string, int>> vec(m.begin(), m.end());
std::sort(vec.begin(), vec.end(), [](auto& a, auto& b) { return a.second < b.second; });
for (auto& p : vec) std::cout << p.first << ":" << p.second << std::endl;
return 0;
}
55. Write a program that implements a stack using a std::vector.
cpp
#include <iostream>
#include <vector>
template<typename T>
class Stack {
std::vector<T> data;
public:
void push(T val) { data.push_back(val); }
void pop() { if (!empty()) data.pop_back(); }
T top() { return data.back(); }
bool empty() { return data.empty(); }
};
int main() {
Stack<int> s;
s.push(10);
s.push(20);
std::cout << s.top() << std::endl;
s.pop();
std::cout << s.top() << std::endl;
return 0;
}
56. Write a program that finds the longest common prefix in an array of strings.
cpp
#include <iostream>
#include <vector>
#include <string>
int main() {
std::vector<std::string> strs = {"flower","flow","flight"};
if (strs.empty()) return 0;
std::string prefix = strs[0];
for (size_t i = 1; i < strs.size(); i++) {
while (strs[i].find(prefix) != 0) {
prefix.pop_back();
if (prefix.empty()) break;
}
}
std::cout << prefix << std::endl;
return 0;
}
57. Write a program that converts a binary string to its decimal equivalent.
cpp
#include <iostream>
#include <string>
int main() {
std::string binary = "1010";
int decimal = std::stoi(binary, nullptr, 2);
std::cout << decimal << std::endl;
return 0;
}
58. Write a program that calculates the average of a vector of doubles.
cpp
#include <iostream>
#include <vector>
int main() {
std::vector<double> v = {1.5, 2.5, 3.5};
double sum = 0;
for (double d : v) sum += d;
std::cout << "Average: " << sum / v.size() << std::endl;
return 0;
}
59. Write a program that uses an enum to represent days of the week and prints a day.
cpp
#include <iostream>
enum Day { MON, TUE, WED, THU, FRI, SAT, SUN };
int main() {
Day d = FRI;
std::cout << d << std::endl; // prints 4
return 0;
}
60. Write a program that prints all permutations of a string (e.g., “ABC”) using recursion.
cpp
#include <iostream>
#include <string>
void permute(std::string str, int l, int r) {
if (l == r) std::cout << str << std::endl;
else {
for (int i = l; i <= r; i++) {
std::swap(str[l], str[i]);
permute(str, l+1, r);
std::swap(str[l], str[i]);
}
}
}
int main() {
std::string s = "ABC";
permute(s, 0, s.length()-1);
return 0;
}
61. Write a program that implements binary search on a sorted array.
cpp
#include <iostream>
#include <vector>
int binarySearch(const std::vector<int>& arr, int x) {
int l = 0, r = arr.size() - 1;
while (l <= r) {
int mid = l + (r - l) / 2;
if (arr[mid] == x) return mid;
if (arr[mid] < x) l = mid + 1;
else r = mid - 1;
}
return -1;
}
int main() {
std::vector<int> arr = {2,5,8,12,16};
std::cout << binarySearch(arr, 12) << std::endl;
return 0;
}
62. Write a program that reverses a singly linked list.
cpp
#include <iostream>
struct Node {
int data;
Node* next;
Node(int d) : data(d), next(nullptr) {}
};
Node* reverse(Node* head) {
Node* prev = nullptr;
Node* curr = head;
while (curr) {
Node* next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
return prev;
}
int main() {
Node* head = new Node(1);
head->next = new Node(2);
head->next->next = new Node(3);
Node* rev = reverse(head);
while (rev) {
std::cout << rev->data << " ";
rev = rev->next;
}
return 0;
}
63. Write a program that uses std::optional (C++17) to avoid null pointer errors.
cpp
#include <iostream>
#include <optional>
std::optional<int> divide(int a, int b) {
if (b == 0) return std::nullopt;
return a / b;
}
int main() {
auto res = divide(10, 0);
std::cout << (res ? std::to_string(*res) : "Error") << std::endl;
return 0;
}
64. Write a program that uses std::transform to convert a vector to uppercase.
cpp
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <cctype>
int main() {
std::vector<std::string> v = {"hello", "world"};
for (auto& s : v) {
std::transform(s.begin(), s.end(), s.begin(), ::toupper);
std::cout << s << std::endl;
}
return 0;
}
65. Write a program that finds the intersection of two std::sets.
cpp
#include <iostream>
#include <set>
#include <algorithm>
int main() {
std::set<int> s1 = {1,2,3};
std::set<int> s2 = {3,4,5};
std::set<int> result;
std::set_intersection(s1.begin(), s1.end(), s2.begin(), s2.end(),
std::inserter(result, result.begin()));
for (int x : result) std::cout << x << " ";
return 0;
}
66. Write a program that uses std::priority_queue to print elements in sorted order.
cpp
#include <iostream>
#include <queue>
int main() {
std::priority_queue<int, std::vector<int>, std::greater<int>> pq;
pq.push(5); pq.push(1); pq.push(3);
while (!pq.empty()) {
std::cout << pq.top() << " ";
pq.pop();
}
return 0;
}
67. Write a program that uses std::chrono to measure time difference in milliseconds.
cpp
#include <iostream>
#include <chrono>
#include <thread>
int main() {
auto start = std::chrono::high_resolution_clock::now();
std::this_thread::sleep_for(std::chrono::milliseconds(500));
auto end = std::chrono::high_resolution_clock::now();
auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
std::cout << ms.count() << " ms" << std::endl;
return 0;
}
68. Write a program that generates a random integer between 1 and 100.
cpp
#include <iostream>
#include <random>
int main() {
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> dis(1, 100);
std::cout << dis(gen) << std::endl;
return 0;
}
69. Write a program that implements a simple calculator using a switch statement.
cpp
#include <iostream>
int main() {
double a, b;
char op;
std::cout << "Enter two numbers and operator (+,-,*,/): ";
std::cin >> a >> b >> op;
double result;
switch (op) {
case '+': result = a + b; break;
case '-': result = a - b; break;
case '*': result = a * b; break;
case '/': result = a / b; break;
default: std::cout << "Invalid operator"; return 1;
}
std::cout << "Result: " << result << std::endl;
return 0;
}
70. Write a program that checks if a number is a perfect number (sum of divisors equals itself).
cpp
#include <iostream>
int main() {
int num = 28;
int sum = 0;
for (int i = 1; i < num; i++) {
if (num % i == 0) sum += i;
}
std::cout << num << (sum == num ? " is perfect" : " is not perfect") << std::endl;
return 0;
}
71. Write a program that uses std::any (C++17) to store different types.
cpp
#include <iostream>
#include <any>
int main() {
std::any value = 42;
std::cout << std::any_cast<int>(value) << std::endl;
value = std::string("Hello");
std::cout << std::any_cast<std::string>(value) << std::endl;
return 0;
}
72. Write a program that uses std::variant (C++17) to store different types.
cpp
#include <iostream>
#include <variant>
int main() {
std::variant<int, double, std::string> v;
v = 42;
std::cout << std::get<int>(v) << std::endl;
v = "Text";
std::cout << std::get<std::string>(v) << std::endl;
return 0;
}
73. Write a program that uses a std::unique_ptr to manage dynamic memory.
cpp
#include <iostream>
#include <memory>
int main() {
std::unique_ptr<int> ptr = std::make_unique<int>(100);
std::cout << *ptr << std::endl;
// automatic deletion
return 0;
}
74. Write a program that copies a file using std::ifstream and std::ofstream.
cpp
#include <fstream>
int main() {
std::ifstream src("input.txt", std::ios::binary);
std::ofstream dst("output.txt", std::ios::binary);
dst << src.rdbuf();
return 0;
}
75. Write a program that implements a simple lambda expression and stores it in a variable.
cpp
#include <iostream>
int main() {
auto add = [](int a, int b) { return a + b; };
std::cout << add(3, 4) << std::endl;
return 0;
}
76. Write a program that uses std::accumulate to sum elements of a vector.
cpp
#include <iostream>
#include <vector>
#include <numeric>
int main() {
std::vector<int> v = {1,2,3,4};
int sum = std::accumulate(v.begin(), v.end(), 0);
std::cout << sum << std::endl;
return 0;
}
77. Write a program that finds the first duplicate element in an array.
cpp
#include <iostream>
#include <unordered_set>
int main() {
int arr[] = {1,2,3,2,4};
std::unordered_set<int> seen;
for (int num : arr) {
if (seen.find(num) != seen.end()) {
std::cout << "First duplicate: " << num << std::endl;
break;
}
seen.insert(num);
}
return 0;
}
78. Write a program that moves all zeros in an array to the end preserving order.
cpp
#include <iostream>
#include <vector>
int main() {
std::vector<int> arr = {0,1,0,3,12};
int pos = 0;
for (int num : arr) {
if (num != 0) arr[pos++] = num;
}
while (pos < arr.size()) arr[pos++] = 0;
for (int x : arr) std::cout << x << " ";
return 0;
}
79. Write a program that implements a simple LRU cache using std::list and std::unordered_map.
cpp
#include <iostream>
#include <list>
#include <unordered_map>
class LRUCache {
int cap;
std::list<int> order;
std::unordered_map<int, std::list<int>::iterator> map;
public:
LRUCache(int capacity) : cap(capacity) {}
void refer(int x) {
if (map.find(x) != map.end()) {
order.erase(map[x]);
} else if (order.size() == cap) {
int last = order.back();
order.pop_back();
map.erase(last);
}
order.push_front(x);
map[x] = order.begin();
}
void display() {
for (int x : order) std::cout << x << " ";
std::cout << std::endl;
}
};
int main() {
LRUCache cache(2);
cache.refer(1); cache.refer(2); cache.refer(1); cache.refer(3);
cache.display(); // 3 1
return 0;
}
80. Write a program that uses std::regex to find all email addresses in a string.
cpp
#include <iostream>
#include <regex>
#include <string>
int main() {
std::string text = "Contact us at john@example.com and jane@example.org";
std::regex pattern(R"([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,})");
std::smatch matches;
std::sregex_iterator it(text.begin(), text.end(), pattern);
std::sregex_iterator end;
while (it != end) {
std::cout << it->str() << std::endl;
++it;
}
return 0;
}
81. Write a program that uses std::sort with a custom comparator to sort strings by length.
cpp
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
int main() {
std::vector<std::string> v = {"cat", "elephant", "dog", "giraffe"};
std::sort(v.begin(), v.end(), [](const std::string& a, const std::string& b) {
return a.length() < b.length();
});
for (auto& s : v) std::cout << s << " ";
return 0;
}
82. Write a program that uses std::filesystem (C++17) to list files in a directory.
cpp
#include <iostream>
#include <filesystem>
namespace fs = std::filesystem;
int main() {
for (const auto& entry : fs::directory_iterator(".")) {
std::cout << entry.path() << std::endl;
}
return 0;
}
83. Write a program that uses std::thread and std::async to run a function asynchronously.
cpp
#include <iostream>
#include <future>
int add(int a, int b) { return a + b; }
int main() {
std::future<int> result = std::async(add, 5, 7);
std::cout << result.get() << std::endl;
return 0;
}
84. Write a program that implements a singleton class (thread‑safe with static local variable).
cpp
#include <iostream>
class Singleton {
public:
static Singleton& getInstance() {
static Singleton instance; // thread-safe since C++11
return instance;
}
void greet() { std::cout << "Hello from Singleton" << std::endl; }
Singleton(const Singleton&) = delete;
void operator=(const Singleton&) = delete;
private:
Singleton() {}
};
int main() {
Singleton::getInstance().greet();
return 0;
}
85. Write a program that uses std::bitset to represent a binary number.
cpp
#include <iostream>
#include <bitset>
int main() {
std::bitset<8> bits(42);
std::cout << bits << std::endl; // 00101010
return 0;
}
86. Write a program that implements a simple producer‑consumer using std::queue and std::mutex.
cpp
#include <iostream>
#include <queue>
#include <thread>
#include <mutex>
#include <condition_variable>
std::queue<int> q;
std::mutex mtx;
std::condition_variable cv;
void producer() {
for (int i = 0; i < 10; i++) {
std::lock_guard<std::mutex> lock(mtx);
q.push(i);
cv.notify_one();
}
}
void consumer() {
for (int i = 0; i < 10; i++) {
std::unique_lock<std::mutex> lock(mtx);
cv.wait(lock, []{ return !q.empty(); });
std::cout << q.front() << " ";
q.pop();
}
}
int main() {
std::thread t1(producer), t2(consumer);
t1.join(); t2.join();
return 0;
}
87. Write a program that converts an integer to its binary representation without using built‑in.
cpp
#include <iostream>
#include <string>
std::string toBinary(int n) {
if (n == 0) return "0";
std::string res;
while (n > 0) {
res = char('0' + (n % 2)) + res;
n /= 2;
}
return res;
}
int main() {
std::cout << toBinary(10) << std::endl; // 1010
return 0;
}
88. Write a program that uses std::tie to unpack a tuple.
cpp
#include <iostream>
#include <tuple>
int main() {
std::tuple<int, double, std::string> t(1, 3.14, "hello");
int i; double d; std::string s;
std::tie(i, d, s) = t;
std::cout << i << " " << d << " " << s << std::endl;
return 0;
}
89. Write a program that uses std::variant and std::visit.
cpp
#include <iostream>
#include <variant>
int main() {
std::variant<int, double> v = 42;
std::visit([](auto&& arg) { std::cout << arg << std::endl; }, v);
v = 3.14;
std::visit([](auto&& arg) { std::cout << arg << std::endl; }, v);
return 0;
}
90. Write a program that implements a simple std::function callback.
cpp
#include <iostream>
#include <functional>
void callMe(std::function<void()> callback) {
callback();
}
int main() {
callMe([]() { std::cout << "Callback executed" << std::endl; });
return 0;
}
91. Write a program that uses std::shuffle to randomly shuffle a vector.
cpp
#include <iostream>
#include <vector>
#include <algorithm>
#include <random>
int main() {
std::vector<int> v = {1,2,3,4,5};
std::random_device rd;
std::mt19937 g(rd());
std::shuffle(v.begin(), v.end(), g);
for (int x : v) std::cout << x << " ";
return 0;
}
92. Write a program that uses std::for_each to print each element of a vector.
cpp
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> v = {1,2,3};
std::for_each(v.begin(), v.end(), [](int x) { std::cout << x << " "; });
return 0;
}
93. Write a program that computes the median of a vector of integers.
cpp
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> v = {3,7,1,9,4};
std::sort(v.begin(), v.end());
double median;
if (v.size() % 2 == 0)
median = (v[v.size()/2 - 1] + v[v.size()/2]) / 2.0;
else
median = v[v.size()/2];
std::cout << "Median: " << median << std::endl;
return 0;
}
94. Write a program that reads integers from standard input until EOF and prints their sum.
cpp
#include <iostream>
int main() {
int sum = 0, x;
while (std::cin >> x) sum += x;
std::cout << "Sum: " << sum << std::endl;
return 0;
}
95. Write a program that implements a simple banking system with deposit and withdrawal using encapsulation.
cpp
#include <iostream>
class BankAccount {
double balance = 0.0;
public:
void deposit(double amount) { balance += amount; }
bool withdraw(double amount) {
if (amount <= balance) { balance -= amount; return true; }
return false;
}
double getBalance() const { return balance; }
};
int main() {
BankAccount acc;
acc.deposit(500);
acc.withdraw(200);
std::cout << "Balance: " << acc.getBalance() << std::endl;
return 0;
}
96. Write a program that prints a triangle pattern of stars for a given height (e.g., 5).
cpp
#include <iostream>
int main() {
int height = 5;
for (int i = 1; i <= height; i++) {
for (int j = 1; j <= i; j++) std::cout << "* ";
std::cout << std::endl;
}
return 0;
}
97. Write a program that prints an inverted triangle pattern.
cpp
#include <iostream>
int main() {
int height = 5;
for (int i = height; i >= 1; i--) {
for (int j = 1; j <= i; j++) std::cout << "* ";
std::cout << std::endl;
}
return 0;
}
98. Write a program that uses std::time and std::localtime to print current time.
cpp
#include <iostream>
#include <ctime>
int main() {
std::time_t t = std::time(nullptr);
std::cout << std::ctime(&t);
return 0;
}
99. Write a program that uses std::numeric_limits to find the maximum value of an int.
cpp
#include <iostream>
#include <limits>
int main() {
std::cout << "Max int: " << std::numeric_limits<int>::max() << std::endl;
return 0;
}
100. Write a program that uses std::stack to reverse a string.
cpp
#include <iostream>
#include <stack>
#include <string>
int main() {
std::string str = "Hello";
std::stack<char> st;
for (char c : str) st.push(c);
while (!st.empty()) {
std::cout << st.top();
st.pop();
}
return 0;
}
Final Thoughts
You’ve reached the end — but in C++, the end is just the call to main() returning 0.
These 100 problems weren’t about memorizing syntax. They were about thinking in pointers, respecting memory, and slowly taming one of the most powerful languages ever built. Whether you wrestled with a tricky template or finally saw your segfault disappear, each hiccup made you sharper.
Bookmark this collection like an old tool chest. C++ rewards those who keep practicing; months from now, revisit a “hard” problem and smile at how easy it now feels. You’re no longer just learning C++. You’re starting to speak it. Keep building, keep debugging, and never forget — every expert was once exactly where you are right now.