Skip to content
Tutorials Center
My learning

Topics

Lesson 163 of 171 ยท Practice and Review

C++ Programs: 40 Classic Examples

40 classic C++ programs with output: prime check, factorial, Fibonacci, palindromes, GCD and LCM, Armstrong numbers, base conversion, sorting, matrices and more.

Every programmer learns a language partly by writing the same small classics: check whether a number is prime, reverse a string, find the second largest value, multiply two matrices. These programs are short enough to read in a minute, yet each one exercises a real skill: loops, integer arithmetic, string handling, containers or algorithms. This page collects 40 of them, written from scratch in modern C++23.

Every program is complete and runs as it is: press Run to compile it on our server and see the output. Change the numbers, break things on purpose, and run again. Programs that read input come with values already in the Input box, so you can edit those too. Each example has a one-line explanation and a link to the lesson that covers the idea in depth.

Two habits show up throughout. First, the programs use the standard library wherever it does the job well (std::gcd, std::ranges::sort, std::format), and they show the hand-written version next to it when the algorithm itself is the point. Second, they pick types on purpose: long long or unsigned long long when values grow fast, std::size_t for indexes and sizes. When you want to write these yourself before reading ours, try the practice exercises first.

Input and basic arithmetic

These practice reading input, arithmetic operators and if statements.

1. Sum and average of numbers

Reads numbers until the input ends and prints how many there were, their sum and their average. The while (std::cin >> n) loop stops cleanly at the end of the input.

C++ 1. Sum and average

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

2. Even or odd

Uses the remainder operator: a number is even when n % 2 == 0. Comparing with 0 (not 1) also works for negative numbers, because -7 % 2 is -1 in C++.

C++ 2. Even or odd

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

3. Largest of three numbers

Shows the explicit if chain and the one-liner with std::max and an initializer list. See Comparison and Logical Operators.

C++ 3. Largest of three

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

4. Swap two numbers

std::swap is the right tool. The arithmetic and XOR tricks are classic interview answers, but they are harder to read and the arithmetic one can overflow.

C++ 4. Swap two numbers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

5. Simple calculator

Reads expressions like 12 * 4, one per line, and evaluates them with a switch on the operator character. Division by zero is reported instead of crashing. See switch Statements.

C++ 5. Simple calculator

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

6. Leap year

A year is a leap year when it's divisible by 4, except century years, unless they're divisible by 400. One boolean expression captures all three rules.

C++ 6. Leap year

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Loops and number theory

These practice loops, functions, recursion and math functions.

7. Factorial

Computes n! with a loop and with recursion. unsigned long long holds factorials up to 20!; 21! no longer fits in 64 bits. See Integer Types.

C++ 7. Factorial

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

8. Fibonacci sequence

Prints the first terms by keeping only the last two values, which is O(n) time and O(1) memory. The naive recursive version recomputes the same terms exponentially often.

C++ 8. Fibonacci sequence

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

9. Prime check

Tests divisors only up to the square root, and only odd ones after 2. Writing the loop condition as d * d <= n avoids floating-point sqrt.

C++ 9. Prime check

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

10. All primes up to N (Sieve of Eratosthenes)

Marks the multiples of each prime as composite in a std::vector<bool>. Finding every prime up to N takes O(N log log N), far faster than testing each number separately. See std::vector.

C++ 10. Sieve of Eratosthenes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

11. GCD and LCM

Euclid's algorithm replaces (a, b) with (b, a % b) until b is zero. The LCM divides before multiplying to avoid overflow. C++17's std::gcd and std::lcm in <numeric> do the same.

C++ 11. GCD and LCM

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

12. Reverse a number and sum its digits

Peels off the last digit with % 10 and drops it with / 10. The same loop body powers palindrome and Armstrong checks below. See while Loops.

C++ 12. Reverse a number

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

13. Palindrome number

A number is a palindrome when it equals its own reverse. Negative numbers are never palindromes because of the minus sign.

C++ 13. Palindrome number

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

14. Armstrong numbers

An Armstrong number equals the sum of its digits, each raised to the number of digits: 153 = 1ยณ + 5ยณ + 3ยณ. The program counts digits first, then uses integer powers so no floating-point rounding creeps in.

C++ 14. Armstrong numbers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

15. Perfect numbers

A perfect number equals the sum of its proper divisors: 28 = 1 + 2 + 4 + 7 + 14. Divisors come in pairs (d, n / d), so the loop only runs to the square root.

C++ 15. Perfect numbers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

16. Fast exponentiation

Squares the base and halves the exponent, so power(3, 40) takes about six steps instead of forty. The modular version is how cryptography computes huge powers. See Recursion.

C++ 16. Fast exponentiation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

17. Multiplication table

Nested loops with fixed-width format specs keep the columns aligned. See Formatting with std::format.

C++ 17. Multiplication table

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

18. Roots of a quadratic equation

Solves axยฒ + bx + c = 0 with the discriminant and handles all three cases: two real roots, one repeated root, or two complex roots.

C++ 18. Quadratic equation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Number bases and bits

These practice bitwise operators and string conversions.

19. Decimal to binary, octal and hexadecimal

std::format converts with the b, o and x types. The hand-written function repeatedly divides by the base and works for any base from 2 to 36.

C++ 19. Decimal to other bases

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

20. Binary (or any base) back to decimal

std::stoi takes a base as its third argument. The manual version multiplies the running value by the base and adds each digit, which is Horner's method.

C++ 20. Other bases to decimal

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

21. Count set bits and test powers of two

n & (n - 1) clears the lowest set bit, so the loop runs once per 1-bit. C++20's <bit> header has std::popcount and std::has_single_bit built in.

C++ 21. Counting bits

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Strings

These practice strings, string methods, characters and std::unordered_map.

22. Reverse a string

Three ways: a reversed copy from reverse iterators, std::ranges::reverse in place, and a two-index swap loop that shows what the algorithm does.

C++ 22. Reverse a string

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

23. Palindrome string

Compares characters from both ends, skipping anything that isn't a letter or digit and ignoring case. The unsigned char cast is required: passing a negative char to <cctype> functions is undefined behavior.

C++ 23. Palindrome string

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

24. Count vowels and consonants

Lowercases each letter and checks it against a string of vowels with contains (C++23). Characters that aren't letters are counted separately.

C++ 24. Vowels and consonants

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

25. Word frequency

Reads words with >> (which splits on whitespace), counts them in a std::map so the output is alphabetical, and finds the most common one. See std::map.

C++ 25. Word frequency

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

26. Anagram check

Two words are anagrams when they use the same letters the same number of times. Counting letters in an array is O(n); sorting both strings and comparing is the shorter alternative.

C++ 26. Anagram check

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

27. Character frequency

Counts every character with std::unordered_map, then copies the pairs into a vector and sorts them by count, a pattern you'll use often because hash maps have no useful order.

C++ 27. Character frequency

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

28. Capitalize every word

Uppercases a letter when the character before it is a space (or it's the first character), and lowercases the rest.

C++ 28. Title case

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

29. Run-length compression

Turns aaabccdddd into a3b1c2d4 by counting runs of equal characters. std::format_to with std::back_inserter appends formatted text straight into the result string.

C++ 29. Run-length encoding

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Arrays and vectors

These practice std::vector, std::array and searching and sorting algorithms.

30. Sum, average, minimum and maximum

std::accumulate sums the values (starting from 0.0 so the sum is a double), and std::ranges::minmax finds both extremes in one pass. See Numeric Algorithms.

C++ 30. Array statistics

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

31. Second largest element

One pass keeps the largest and second largest distinct values. std::optional reports "no answer" when every element is equal or there's only one.

C++ 31. Second largest

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Linear search checks every element (O(n)) and works on any data. Binary search halves a sorted range each step (O(log n)); std::ranges::lower_bound is the standard version.

C++ 32. Linear and binary search

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

33. Bubble sort

Swaps neighbors that are out of order, so the largest remaining value "bubbles" to the end of each pass. The swapped flag stops early on sorted input. It's O(nยฒ): in real code, call std::ranges::sort.

C++ 33. Bubble sort

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

34. Rotate an array

std::ranges::rotate moves a chosen element to the front. The reversal trick (reverse the two parts, then the whole) does the same in place with O(1) extra memory.

C++ 34. Rotate an array

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

35. Remove duplicates

Sort, then std::ranges::unique packs the unique values at the front and returns the leftover tail to erase. To keep the original order instead, remember seen values in a std::unordered_set. See std::set.

C++ 35. Remove duplicates

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

36. Merge two sorted vectors

Walks both inputs with two indexes and always takes the smaller front element: the heart of merge sort. std::ranges::merge does the same.

C++ 36. Merge sorted vectors

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Matrices

These practice multidimensional arrays.

37. Matrix addition and multiplication

Stores matrices as std::vector<std::vector<int>>. Entry (i, j) of a product is the dot product of row i of the first matrix and column j of the second, so the inner sizes must match.

C++ 37. Matrix add and multiply

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

38. Transpose a matrix

Swaps rows and columns: element (i, j) moves to (j, i), so a 2ร—3 matrix becomes 3ร—2. Printing row by row makes the shape visible.

C++ 38. Matrix transpose

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Patterns and classes

These practice nested loops, classes and operator overloading.

39. Pyramid and Pascal's triangle

The pyramid centers each row with leading spaces. Each Pascal's triangle entry is computed from the one before it in the same row with C(n, k+1) = C(n, k) * (n - k) / (k + 1), which stays exact in integers.

C++ 39. Pyramid and Pascal's triangle

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

40. A Fraction class

A small value type: the constructor normalizes the sign and reduces with std::gcd, operator+ and operator* return new fractions, and a std::formatter specialization lets std::println print it. It ties together constructors, operator overloading and exceptions.

C++ 40. A Fraction class

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Because the constructor isn't explicit, half + half == 1 converts 1 to Fraction{1, 1} automatically. That's convenient for a number-like type; for most other classes, mark single-argument constructors explicit so conversions don't surprise you.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. The sieve (program 10) starts crossing out multiples of n at n * n. Why is that safe?

    Any composite k * n with k < n has a prime factor smaller than n (one of k's factors), so that prime's pass already marked it.
  2. 2. What does the reverse-a-number loop compute for n = 1200?

    The reversed value is built as an integer, and integers have no leading zeros, so 1200 reverses to 21.
  3. 3. In program 23, why are characters cast to unsigned char before calling std::isalnum and std::tolower?

    The <cctype> functions take an int that must be representable as unsigned char or equal EOF. Bytes above 127 are negative in a signed char.
  4. 4. Which value does factorial(21) produce with an unsigned long long result?

    Unsigned overflow is well defined in C++ (it wraps modulo 2^64), so you silently get a wrong number. 20! is the largest factorial that fits.

Summary

  • Number classics (primes, GCD, digits, powers) come down to %, / and loops that stop early: square-root bounds, Euclid's algorithm and halving exponents.
  • Choose types deliberately: wider integers for fast-growing values, std::size_t for indexes, unsigned char before <cctype> calls.
  • String classics combine character tests, two-index scans and counting with maps or arrays.
  • Array classics show the hand-written algorithm, but the standard versions (std::ranges::sort, unique, rotate, merge, lower_bound) are what you use in real code.
  • Small value classes like Fraction become pleasant to use with normalizing constructors, operator overloading and a std::formatter.

Next: C++ Practice Exercises, where you write programs like these yourself and compare your solutions with ours.