C++ Programming · Practice by type
C++ Programming Programs for Practice with Output
Practice programs for every C++ Programming topic, each with a full solution, its real output and an explanation. Try writing each one yourself first.
- 270 questions
- 27 topics
- Answers checked on a real compiler
Basic Syntax and Data Types 10 questions
- Swap two numbers in C++ (three ways) Easy
- Sum and reverse the digits of a number in C++ Easy
- Convert seconds to hh:mm:ss in C++ with std::format Easy
- Simple interest and loan EMI calculator in C++ Medium
- Check leap years in C++ Easy
- Print ASCII values of characters in a string in C++ Easy
- Print ranges of C++ data types with numeric_limits Medium
- Read marks and print total, average and grade in C++ Easy
- BMI calculator with input and category in C++ Easy
- Simple calculator using switch in C++ Easy
Input/Output with cin and cout 10 questions
- Sum, average, minimum and maximum of n numbers in C++ Easy
- Print an aligned invoice table with setw and setfill in C++ Medium
- Read an ID, full name and address with getline in C++ Easy
- Keep asking until a valid age is entered in C++ Medium
- Count lines, words and characters from input in C++ Medium
- Parse CSV sales data with stringstream in C++ Medium
- Formatted multiplication table with std::format in C++ Easy
- Show a number in decimal, hex, octal and binary in C++ Medium
- Read key=value settings, skipping comments, in C++ Hard
- Fast input: sum of many numbers with sync_with_stdio in C++ Medium
Functions and Default Arguments 10 questions
- GCD and LCM of two numbers using recursion in C++ Easy
- Fast exponentiation (power) with recursion in C++ Medium
- Area of shapes with function overloading in C++ Easy
- Rotate three variables using references in C++ Easy
- Check palindromes recursively in C++ Medium
- Return min, max, mean and median with a struct in C++ Medium
- Memoized Fibonacci with a static cache in C++ Medium
- Tower of Hanoi: count and list the moves in C++ Medium
- Calculator with a table of std::function operations in C++ Hard
- Count ways to climb stairs (1 or 2 steps) recursively in C++ Medium
Arrays and Vectors 10 questions
- Reverse an array in place in C++ Easy
- Find the second largest element in one pass in C++ Medium
- Rotate a vector left by k positions in C++ Medium
- Merge two sorted vectors in C++ Medium
- Remove duplicates from a vector in C++ Easy
- Matrix multiplication with 2D vectors in C++ Medium
- Count digit frequencies with an array in C++ Easy
- Maximum subarray sum (Kadane's algorithm) in C++ Hard
- Find pairs with a given sum using two pointers in C++ Medium
- Answer range sum queries with prefix sums in C++ Medium
std::string 10 questions
- Check whether a string is a palindrome in C++ Easy
- Count vowels, consonants, digits and spaces in C++ Easy
- Reverse each word of a sentence in C++ Medium
- Check whether two strings are anagrams in C++ Medium
- Character frequency with std::map in C++ Easy
- Capitalize the first letter of every word in C++ Easy
- Find the longest word in a sentence in C++ Easy
- Compress a string by counting repeated characters in C++ Medium
- First non-repeating character in a string in C++ Medium
- Remove duplicate characters from a string in C++ Medium
Pointers and Dynamic Memory 10 questions
- Return minimum and maximum through pointer parameters in C++ Easy
- Reverse an array using two pointers in C++ Easy
- Length and copy of a C string with pointers in C++ Medium
- A growable array with new[] and delete[] in C++ Hard
- Dynamic matrix: read, transpose and free in C++ Medium
- Singly linked list: insert, delete and print in C++ Hard
- Reverse a linked list in place in C++ Medium
- Count letters and digits with a char pointer in C++ Easy
- Merge two sorted arrays into a new dynamic array in C++ Medium
- An RAII class that owns a dynamic array in C++ Hard
References: lvalue and rvalue 10 questions
- Sort three numbers using reference parameters in C++ Easy
- Update student records in place with auto& in C++ Easy
- Sum, mean and maximum via reference parameters in C++ Easy
- Word counter using a reference to map values in C++ Medium
- Swap matrix rows and scale a row through references in C++ Medium
- Class with reference-returning accessors in C++ Medium
- Count copies and moves of a class in C++ Hard
- A logging wrapper with perfect forwarding in C++ Hard
- Fill results from threads using std::ref in C++ Hard
- Trim and lowercase a string in place in C++ Medium
OOPS Concepts 10 questions
- Bank account class with deposit and withdraw in C++ Easy
- Rectangle class with area, perimeter and comparison in C++ Easy
- Shape hierarchy with virtual area and perimeter in C++ Medium
- Employee and Manager classes with inheritance in C++ Medium
- Student class with static count and class average in C++ Easy
- Library and Book classes using composition in C++ Medium
- Complex number class with operator overloading in C++ Medium
- A bounded Stack class with encapsulation in C++ Medium
- Temperature class with getters and setters in C++ Easy
- Vehicle interface with fuel cost calculation in C++ Hard
Classes and Objects 10 questions
- Date class with validation and next day in C++ Medium
- Fraction class with reduction and arithmetic in C++ Medium
- 2x2 matrix class with multiply, determinant and power in C++ Hard
- Student report card with an array of objects in C++ Easy
- Inventory class managing a vector of items in C++ Medium
- Point class: distance, midpoint and centroid in C++ Easy
- Polynomial class: evaluate, add and differentiate in C++ Hard
- Fixed-size circular queue class in C++ Hard
- Time class that adds durations and wraps at midnight in C++ Medium
- User registry with auto-generated IDs in C++ Medium
Constructors and Destructors 10 questions
- Dynamic array class with the rule of five in C++ Hard
- A simple String class with deep copy in C++ Medium
- Bank account with delegating constructors in C++ Medium
- A move-only resource handle class in C++ Hard
- RAII scope logger that reports on every exit in C++ Medium
- Track created, copied and destroyed objects in C++ Medium
- Fraction class with a validating constructor in C++ Easy
- Stack class with an initializer_list constructor in C++ Medium
- Polymorphic copying with a virtual clone() function in C++ Hard
- Matrix class with several constructors in C++ Medium
Static and Friend Members 10 questions
- Thread-safe singleton configuration manager in C++ Medium
- Savings accounts sharing a static interest rate in C++ Easy
- Count created and currently alive objects in C++ Medium
- Friend stream operators for a Point class in C++ Easy
- Money class with symmetric friend operators in C++ Medium
- A friend diagnostics class for a sensor in C++ Medium
- One friend function shared by two classes in C++ Medium
- A reusable per-class instance counter with CRTP in C++ Hard
- Static factory with a cache (flyweight) in C++ Hard
- Matrix-vector multiplication with a friend operator in C++ Medium
Encapsulation 10 questions
- Bank account with a read-only transaction history in C++ Medium
- Password class enforcing a password policy in C++ Medium
- Grade book with validated marks and a cached average in C++ Medium
- An immutable Money value type in C++ Medium
- Order lifecycle as an encapsulated state machine in C++ Hard
- Inventory with stock levels and reorder alerts in C++ Medium
- Range-limited temperature controller with clamping in C++ Easy
- Matrix class with bounds-checked access in C++ Medium
- Logger class using the pimpl idiom in C++ Hard
- Library membership with behaviour instead of setters in C++ Medium
Inheritance 10 questions
- Vehicle, Car and ElectricCar: multilevel inheritance in C++ Easy
- Hierarchical inheritance: shapes sharing base data in C++ Easy
- Student-athlete with multiple inheritance in C++ Medium
- Copier: diamond problem with virtual inheritance in C++ Hard
- Custom exception hierarchy in C++ Medium
- Savings and current accounts with a shared base in C++ Medium
- GUI widget hierarchy with base and derived drawing in C++ Medium
- Animals sharing a base class in C++ Easy
- A counting stack built on a base container in C++ Medium
- Hybrid inheritance: teaching assistant class in C++ Hard
Polymorphism and Virtual Functions 10 questions
- Payment gateway with polymorphic payment methods in C++ Medium
- Notification system with interchangeable channels in C++ Easy
- Game characters with virtual attack and damage in C++ Medium
- Export a report as CSV or JSON with polymorphism in C++ Medium
- Sort a mixed collection of shapes by area in C++ Medium
- A plugin registry that creates objects by name in C++ Hard
- Shapes with std::variant and visitors in C++ Hard
- CRTP mixin that adds comparisons and printing in C++ Hard
- Data import pipeline with the NVI pattern in C++ Medium
- Bank account month-end interest with polymorphism in C++ Medium
Abstraction 10 questions
- Bank account abstraction with deposit and withdraw in C++ Easy
- Shopping cart class hiding prices and discounts in C++ Medium
- Key-value store with swappable storage backends in C++ Medium
- RAII scope logger that reports when each block ends in C++ Medium
- Matrix class that hides its flat storage in C++ Medium
- Generic mean, median and mode with concepts in C++ Hard
- Logger interface with console and filter loggers in C++ Medium
- Task scheduler ADT backed by a priority queue in C++ Medium
- Unit-safe distance and speed types in C++ Hard
- Library catalog with issue and return operations in C++ Medium
Abstract Classes and Interfaces 10 questions
- Vehicle rental system with an abstract Vehicle class in C++ Easy
- Sensor dashboard built on a Sensor interface in C++ Medium
- Exporting student marks to CSV, TSV and Markdown in C++ Medium
- Ride fare calculator with swappable pricing rules in C++ Medium
- Unit testing a service with a mock interface in C++ Hard
- Text processing pipeline of interchangeable stages in C++ Medium
- Game entities implementing Movable and Damageable in C++ Hard
- Turn-based game skeleton with an abstract class in C++ Medium
- Payment gateway interface with a factory and refunds in C++ Hard
- Shape area report with is_abstract checks in C++ Medium
Operator Overloading 10 questions
- Fraction class with arithmetic operators in C++ Medium
- Big integer + and * with operator overloading in C++ Hard
- Polynomial addition, multiplication and evaluation in C++ Medium
- Date class with + days and date difference in C++ Hard
- Matrix class with +, *, == and transpose operators in C++ Medium
- String builder using operator<< for chaining in C++ Easy
- Money class with safe arithmetic and GST in C++ Medium
- Type-safe permission flags with |, & and ~ operators in C++ Hard
- Ranking cricket players with a custom <=> in C++ Medium
- Circular buffer with a wrapping operator[] in C++ Medium
Templates 10 questions
- Generic binary search function template in C++ Easy
- Matrix class template with compile-time dimensions in C++ Hard
- Variadic min, max and average of any arguments in C++ Medium
- Type-safe event bus with templates in C++ Hard
- Generic LRU cache class template in C++ Hard
- Safe string-to-number parsing template in C++ Medium
- Join any container into a string with a separator in C++ Easy
- Compile-time lookup tables with constexpr templates in C++ Hard
- Running statistics class template for any number type in C++ Medium
- Print every element of a std::tuple with templates in C++ Hard
STL Containers 10 questions
- Top K frequent words with map and priority_queue in C++ Medium
- Sliding window maximum using a deque in C++ Hard
- Group anagrams using a map of sorted keys in C++ Medium
- Browser back and forward history with two stacks in C++ Medium
- Live leaderboard with map and multimap in C++ Hard
- Job scheduler with priorities and arrival order in C++ Medium
- Two-sum and pair counting with unordered_map in C++ Easy
- Inventory manager with map and low-stock report in C++ Easy
- Shortest path in a grid with BFS and a queue in C++ Hard
- Merge overlapping meeting intervals with a vector in C++ Medium
STL Algorithms and Iterators 10 questions
- Palindrome checker using std::equal and iterators in C++ Easy
- Dense ranking of scores with lower_bound in C++ Medium
- Kth largest element and median with nth_element in C++ Medium
- Run-length encoding using std::find_if in C++ Medium
- Binary search on the answer with partition_point in C++ Hard
- Parse and analyse CSV-like data with ranges in C++ Hard
- Matrix row and column sums with iota and transform in C++ Easy
- Merge sorted log files by timestamp with std::merge in C++ Medium
- Clean up usernames with erase_if and unique in C++ Easy
- Combine parallel lists with views::zip in C++23 Hard
Lambda Expressions 10 questions
- Calculator using a map of lambdas in C++ Easy
- Memoised Fibonacci with a caching lambda in C++ Hard
- Form validation with a list of lambda rules in C++ Medium
- Sort employees by several criteria with lambdas in C++ Medium
- Retry helper that takes an operation as a lambda in C++ Medium
- Scope guard that runs a lambda on exit in C++ Hard
- Function composition pipeline with lambdas in C++ Hard
- Rate limiter with a mutable lambda in C++ Medium
- GUI-style buttons with lambda callbacks in C++ Easy
- Generic group-by function taking a key lambda in C++ Medium
Smart Pointers 10 questions
- Singly linked list built with unique_ptr in C++ Medium
- Shape factory returning unique_ptr from text commands in C++ Easy
- Shared document for several editors with shared_ptr in C++ Medium
- Observer pattern with weak_ptr subscribers in C++ Hard
- Undo and redo with a stack of unique_ptr commands in C++ Medium
- Org chart with shared_ptr and weak_ptr links in C++ Hard
- Connection pool with a custom unique_ptr deleter in C++ Hard
- Pimpl idiom with unique_ptr in C++ Medium
- Texture cache that frees unused entries with weak_ptr in C++ Medium
- Temporary file with a unique_ptr FILE handle in C++ Medium
Move Semantics 10 questions
- Dynamic array class implementing the rule of five in C++ Hard
- Move-only temporary file wrapper class in C++ Medium
- Generic factory with perfect forwarding in C++ Hard
- Efficient string concatenation with rvalue overloads in C++ Medium
- Sort heavy objects with moves, not copies, in C++ Medium
- Message queue that moves messages in and out in C++ Medium
- See how a move steals a vector buffer in C++ Easy
- Count copies and moves with emplace_back in C++ Medium
- Text pipeline moving strings between stages in C++ Medium
- Move polymorphic objects without slicing in C++ Hard
Modern C++ Features (C++11 to C++23) 10 questions
- Key=value config parser with optional and string_view in C++ Medium
- JSON-like value type with std::variant and recursion in C++ Hard
- CSV bill with string_view and std::format in C++ Medium
- Sign-up validation returning std::expected errors in C++23 Hard
- Area and perimeter of shapes stored as std::variant in C++ Medium
- Word frequency counter written in modern C++ style Easy
- Compile-time CRC-style checksum table with consteval in C++ Hard
- Server settings with designated initialisers in C++ Easy
- Property bag of mixed types with std::any in C++ Medium
- Refactor an old-style C++ program into modern C++ Medium
Exception Handling 10 questions
- Safe calculator that reports errors with exceptions in C++ Easy
- Bank transfer with rollback using exceptions in C++ Medium
- Read and validate user input with exceptions in C++ Medium
- Retry a flaky operation and give up after N attempts in C++ Medium
- Application error hierarchy with a top-level handler in C++ Hard
- Guaranteed cleanup with RAII when processing fails in C++ Medium
- Matrix class that throws on dimension mismatch in C++ Medium
- Collect errors from worker threads with exception_ptr in C++ Hard
- Same parser with exceptions and with std::expected in C++ Hard
- Scoped transaction that rolls back unless committed in C++ Hard
File Handling (fstream) 10 questions
- Save and load student records to a text file in C++ Easy
- Word frequency of a text file in C++ Medium
- Binary record database with find and update in C++ Hard
- Filter ERROR lines from a log file into another file in C++ Easy
- Merge two sorted number files into one in C++ Medium
- Read a key=value configuration file with defaults in C++ Medium
- File statistics tool like wc in C++ Easy
- Daily attendance log appended across program runs in C++ Medium
- Organise files by extension with std::filesystem Hard
- Write a file's lines in reverse order and numbered in C++ Easy
Multithreading 10 questions
- Parallel sum of a large array with N threads in C++ Easy
- Simple thread pool with a task queue in C++ Hard
- Count primes in parallel with an atomic counter in C++ Medium
- Thread-safe bank with per-account mutexes in C++ Medium
- Three-stage thread pipeline with blocking queues in C++ Hard
- Parallel matrix multiplication by rows in C++ Medium
- Concurrent checksums with std::async in C++ Easy
- Read-mostly cache with shared_mutex in C++ Hard
- Phased heat simulation with std::barrier in C++ Hard
- Parallel search with jthread and stop_token in C++ Medium
Ready to test your Programming?
Timed online tests with instant scores and explanations.