Programming

54 C++ Programs for Beginners, With Output

From cout and cin to classes, vectors and the standard library: every program compiled as C++17, run, and shown with its exact output.

Modern Age Coders Team
Modern Age Coders Team November 15, 2026
23 min read
54 C++ programs for beginners with code and output

Here are 54 C++ programs for beginners, each with its full code and the exact output it printed when we compiled it as C++17 and ran it. They begin with cout, cin and basic operators, then cover decisions, loops and number programs, patterns, arrays and vectors, strings, functions and recursion, classes and objects, and the standard library (sort, map, set), exceptions and files.

Every program is complete: copy it into a .cpp file, compile, and you should see the same output. Programs that read input show the screen exactly as it looked, including what we typed. If you already know C, the C++ style here (strings, vectors, references and classes) is the part to focus on; if you are new to both, our C programs for beginners list covers the shared basics more slowly.

â„šī¸

How these were tested

Every program was saved as a .cpp file, compiled with c++ -std=c++17 -Wall -Wextra (Apple clang 17) with zero warnings, and run in a terminal. The output boxes are copied from that run. g++ on Windows or Linux gives the same output, except where we say sizes can differ.

How to compile and run a C++ program

C++ is compiled: the compiler turns your .cpp file into a program, and then you run that program.

  • Windows: install g++ through MinGW-w64, or use an IDE that includes a compiler, such as Code::Blocks or Visual Studio.
  • Mac: run xcode-select --install to get clang; the c++ and g++ commands both work after that.
  • Linux: install the g++ or build-essential package.
Terminal
c++ -std=c++17 hello.cpp -o hello   # compile (g++ works the same way)
./hello                             # run (on Windows: hello.exe)

The -std=c++17 flag matters for a few programs here: gcd(), lcm() and the [word, count] loop in the map program need C++17 or newer.

The same task in C and C++ side by side: printf and scanf versus cout and cin, char arrays versus string, fixed arrays versus vector, and pointers versus references
Same ideas, different tools. These four swaps are most of what changes when you move from C to C++.

All 54 C++ programs at a glance

Use this as a practice checklist. The programs get harder as the numbers go up, so a complete beginner can work straight down the list.

No. Program Topic
1 Hello, World Basics
2 Add two numbers entered by the user Basics
3 Swap two numbers Basics
4 Data types and sizeof Basics
5 Area and perimeter of a rectangle Basics
6 Celsius to Fahrenheit with fixed decimals Basics
7 Arithmetic operators and integer division Basics
8 Even or odd Decisions
9 Largest of three numbers Decisions
10 Leap year check Decisions
11 Calculator using switch Decisions
12 Grade from marks Decisions
13 Sum of the first n natural numbers Loops and number programs
14 Factorial Loops and number programs
15 Fibonacci series Loops and number programs
16 Prime number check Loops and number programs
17 Reverse a number and check for a palindrome Loops and number programs
18 Armstrong numbers Loops and number programs
19 GCD and LCM Loops and number programs
20 Sum of digits with do-while Loops and number programs
21 Multiplication table Loops and number programs
22 Right triangle of stars Pattern programs
23 Pyramid of stars Pattern programs
24 Diamond of stars Pattern programs
25 Pascal's triangle Pattern programs
26 Sum, average, largest and smallest in an array Arrays and vectors
27 Vector basics Arrays and vectors
28 Reverse a vector Arrays and vectors
29 Linear search in a vector Arrays and vectors
30 Bubble sort Arrays and vectors
31 Binary search Arrays and vectors
32 Matrix multiplication with 2D vectors Arrays and vectors
33 String basics Strings
34 Palindrome string Strings
35 Count vowels, consonants and words Strings
36 Read a full line of text Strings
37 Change case and reverse words Strings
38 Pass by value vs pass by reference Functions, references and recursion
39 Function overloading Functions, references and recursion
40 Default arguments Functions, references and recursion
41 Recursion: factorial, power and sum of digits Functions, references and recursion
42 Tower of Hanoi Functions, references and recursion
43 A first class: Rectangle Classes and objects (OOP)
44 Bank account class with validation Classes and objects (OOP)
45 Constructors and destructors Classes and objects (OOP)
46 Inheritance Classes and objects (OOP)
47 Polymorphism with virtual functions Classes and objects (OOP)
48 Operator overloading Classes and objects (OOP)
49 Function templates Classes and objects (OOP)
50 Sorting with std::sort The standard library, exceptions and files
51 Word frequency with map The standard library, exceptions and files
52 Remove duplicates with set The standard library, exceptions and files
53 Exception handling The standard library, exceptions and files
54 Write and read a file with fstream The standard library, exceptions and files

C++ programs for beginners as a PDF

To keep a printable copy, open this page and press Ctrl+P (Cmd+P on a Mac), then choose "Save as PDF". Every program and output prints in order. You will learn far more, though, by typing each program yourself and comparing your output with ours.

Basics: cout, cin, variables and operators

C++ prints with cout and reads with cin, both from <iostream>. Start here even if you know C: the style is different.

1. Hello, World

Task: Print a message on the screen.

#include <iostream>
using namespace std;

int main() {
    cout << "Hello, World!" << endl;
    return 0;
}
Output
Hello, World!

using namespace std; lets you write cout instead of std::cout. It is fine in small programs; larger projects usually write std:: in full.

2. Add two numbers entered by the user

Task: Read two integers with cin and print their sum.

#include <iostream>
using namespace std;

int main() {
    int a, b;
    cout << "Enter two numbers: ";
    cin >> a >> b;
    cout << "Sum = " << a + b << endl;
    return 0;
}
Output (typed input included)
Enter two numbers: 38 4
Sum = 42

cin >> a >> b reads two values separated by a space or a new line. No & is needed, unlike scanf() in C.

3. Swap two numbers

Task: Swap two variables with a temporary variable and with std::swap.

#include <iostream>
using namespace std;

int main() {
    int a = 4, b = 11;
    int temp = a;
    a = b;
    b = temp;
    cout << "After manual swap: a = " << a << ", b = " << b << endl;
    swap(a, b);
    cout << "After std::swap:   a = " << a << ", b = " << b << endl;
    return 0;
}
Output
After manual swap: a = 11, b = 4
After std::swap:   a = 4, b = 11

4. Data types and sizeof

Task: Print the size of the common data types and a value of each.

#include <iostream>
using namespace std;

int main() {
    int i = 42;
    double d = 3.14159;
    char c = 'Z';
    bool ok = true;
    string s = "C++";
    cout << "int " << i << " uses " << sizeof(i) << " bytes" << endl;
    cout << "double " << d << " uses " << sizeof(d) << " bytes" << endl;
    cout << "char " << c << " uses " << sizeof(c) << " byte" << endl;
    cout << "bool " << ok << " uses " << sizeof(ok) << " byte" << endl;
    cout << "string " << s << " has " << s.size() << " characters" << endl;
    return 0;
}
Output
int 42 uses 4 bytes
double 3.14159 uses 8 bytes
char Z uses 1 byte
bool 1 uses 1 byte
string C++ has 3 characters

A bool prints as 1 or 0 unless you add boolalpha. Sizes can differ between systems; these are from a 64-bit Mac.

5. Area and perimeter of a rectangle

Task: Calculate the area and perimeter of a rectangle.

#include <iostream>
using namespace std;

int main() {
    double length = 12.5, width = 4.0;
    cout << "Area = " << length * width << endl;
    cout << "Perimeter = " << 2 * (length + width) << endl;
    return 0;
}
Output
Area = 50
Perimeter = 33

6. Celsius to Fahrenheit with fixed decimals

Task: Convert temperatures and print them with one decimal place.

#include <iostream>
using namespace std;
#include <iomanip>

int main() {
    double celsius[] = {-40, 0, 36.6, 100};
    cout << fixed << setprecision(1);
    for (double c : celsius)
        cout << setw(6) << c << " C = " << setw(6) << c * 9 / 5 + 32 << " F" << endl;
    return 0;
}
Output
 -40.0 C =  -40.0 F
   0.0 C =   32.0 F
  36.6 C =   97.9 F
 100.0 C =  212.0 F

fixed and setprecision(1) from <iomanip> control decimals; setw(6) pads each number to 6 characters so the columns line up. At −40 both scales agree.

7. Arithmetic operators and integer division

Task: Show what each arithmetic operator gives for 17 and 5.

#include <iostream>
using namespace std;

int main() {
    int a = 17, b = 5;
    cout << "a + b = " << a + b << endl;
    cout << "a - b = " << a - b << endl;
    cout << "a * b = " << a * b << endl;
    cout << "a / b = " << a / b << "   (integer division)" << endl;
    cout << "a % b = " << a % b << "   (remainder)" << endl;
    cout << "a / 5.0 = " << a / 5.0 << endl;
    return 0;
}
Output
a + b = 22
a - b = 12
a * b = 85
a / b = 3   (integer division)
a % b = 2   (remainder)
a / 5.0 = 3.4

Two int values divide to an int, so 17 / 5 is 3. Make one side a decimal (5.0) to get 3.4.

Decisions: if, else and switch

The same decision tools as C, with bool as a real type and string values you can compare with ==.

8. Even or odd

Task: Read a number and say whether it is even or odd.

#include <iostream>
using namespace std;

int main() {
    int n;
    cout << "Enter a number: ";
    cin >> n;
    if (n % 2 == 0)
        cout << n << " is even" << endl;
    else
        cout << n << " is odd" << endl;
    return 0;
}
Output (typed input included)
Enter a number: 1024
1024 is even

9. Largest of three numbers

Task: Find the largest of three numbers with if-else, then with max().

#include <iostream>
using namespace std;
#include <algorithm>

int main() {
    int a = 31, b = 76, c = 54;
    int largest;
    if (a >= b && a >= c) largest = a;
    else if (b >= c) largest = b;
    else largest = c;
    cout << "Largest (if-else): " << largest << endl;
    cout << "Largest (max):     " << max({a, b, c}) << endl;
    return 0;
}
Output
Largest (if-else): 76
Largest (max):     76

max({a, b, c}) takes a list in braces and needs <algorithm>.

10. Leap year check

Task: Check several years using a bool function.

#include <iostream>
using namespace std;

bool isLeap(int y) {
    return (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
}

int main() {
    for (int y : {1900, 2000, 2024, 2025})
        cout << y << (isLeap(y) ? " is" : " is not") << " a leap year" << endl;
    return 0;
}
Output
1900 is not a leap year
2000 is a leap year
2024 is a leap year
2025 is not a leap year

11. Calculator using switch

Task: Perform an arithmetic operation chosen by the user.

#include <iostream>
using namespace std;

int main() {
    double a, b;
    char op;
    cout << "Enter expression (e.g. 6 * 7): ";
    cin >> a >> op >> b;
    switch (op) {
        case '+': cout << a + b << endl; break;
        case '-': cout << a - b << endl; break;
        case '*': cout << a * b << endl; break;
        case '/':
            if (b == 0) cout << "Cannot divide by zero" << endl;
            else cout << a / b << endl;
            break;
        default: cout << "Unknown operator" << endl;
    }
    return 0;
}
Output (typed input included)
Enter expression (e.g. 6 * 7): 9 * 12
108

12. Grade from marks

Task: Print a grade for each mark in a list.

#include <iostream>
using namespace std;

int main() {
    int marks[] = {95, 81, 67, 49, 30};
    for (int m : marks) {
        char g;
        if (m >= 90) g = 'A';
        else if (m >= 75) g = 'B';
        else if (m >= 60) g = 'C';
        else if (m >= 40) g = 'D';
        else g = 'F';
        cout << m << " -> " << g << endl;
    }
    return 0;
}
Output
95 -> A
81 -> B
67 -> C
49 -> D
30 -> F

Loops and number programs

for, while, do-while and the range-based for loop, used on the classic number problems.

13. Sum of the first n natural numbers

Task: Add 1 to n with a loop and check it with the formula n(n+1)/2.

#include <iostream>
using namespace std;

int main() {
    int n = 50, sum = 0;
    for (int i = 1; i <= n; i++)
        sum += i;
    cout << "Loop: " << sum << ", formula: " << n * (n + 1) / 2 << endl;
    return 0;
}
Output
Loop: 1275, formula: 1275

14. Factorial

Task: Find factorials from 1 to 15.

#include <iostream>
using namespace std;

int main() {
    long long fact = 1;
    for (int i = 1; i <= 15; i++) {
        fact *= i;
        if (i % 5 == 0)
            cout << i << "! = " << fact << endl;
    }
    return 0;
}
Output
5! = 120
10! = 3628800
15! = 1307674368000

long long holds at least 64 bits, enough for factorials up to 20!. An int would overflow at 13!.

15. Fibonacci series

Task: Print the Fibonacci numbers below 200.

#include <iostream>
using namespace std;

int main() {
    int a = 0, b = 1;
    while (a < 200) {
        cout << a << " ";
        int next = a + b;
        a = b;
        b = next;
    }
    cout << endl;
    return 0;
}
Output
0 1 1 2 3 5 8 13 21 34 55 89 144 

16. Prime number check

Task: Check whether a number is prime.

#include <iostream>
using namespace std;

int main() {
    int n;
    cout << "Enter a number: ";
    cin >> n;
    bool prime = n > 1;
    for (int i = 2; i * i <= n; i++)
        if (n % i == 0) { prime = false; break; }
    cout << n << (prime ? " is prime" : " is not prime") << endl;
    return 0;
}
Output (typed input included)
Enter a number: 221
221 is not prime

221 looks prime, but it is 13 × 17.

17. Reverse a number and check for a palindrome

Task: Reverse the digits of a number and say whether it is a palindrome.

#include <iostream>
using namespace std;

int main() {
    int n = 43234, original = n, rev = 0;
    while (n > 0) {
        rev = rev * 10 + n % 10;
        n /= 10;
    }
    cout << "Reversed: " << rev << endl;
    cout << original << (rev == original ? " is" : " is not") << " a palindrome" << endl;
    return 0;
}
Output
Reversed: 43234
43234 is a palindrome

18. Armstrong numbers

Task: Print all Armstrong numbers below 10000.

#include <iostream>
using namespace std;
#include <string>
#include <cmath>

int main() {
    for (int n = 1; n < 10000; n++) {
        int digits = to_string(n).size(), sum = 0;
        for (int t = n; t > 0; t /= 10)
            sum += pow(t % 10, digits);
        if (sum == n) cout << n << " ";
    }
    cout << endl;
    return 0;
}
Output
1 2 3 4 5 6 7 8 9 153 370 371 407 1634 8208 9474 

An Armstrong number equals the sum of its digits each raised to the number of digits, so 1634 = 14 + 64 + 34 + 44.

19. GCD and LCM

Task: Find the GCD and LCM of two numbers with std::gcd and std::lcm.

#include <iostream>
using namespace std;
#include <numeric>

int main() {
    int a = 84, b = 120;
    cout << "GCD = " << gcd(a, b) << endl;
    cout << "LCM = " << lcm(a, b) << endl;
    return 0;
}
Output
GCD = 12
LCM = 840

gcd() and lcm() arrived in C++17 in <numeric>. Write Euclid's loop yourself once (as in our C list), then use the library.

20. Sum of digits with do-while

Task: Find the sum of the digits of a number.

#include <iostream>
using namespace std;

int main() {
    long long n = 9081726354LL;
    int sum = 0;
    do {
        sum += n % 10;
        n /= 10;
    } while (n > 0);
    cout << "Sum of digits = " << sum << endl;
    return 0;
}
Output
Sum of digits = 45

21. Multiplication table

Task: Print the multiplication table of 13 in neat columns.

#include <iostream>
using namespace std;
#include <iomanip>

int main() {
    for (int i = 1; i <= 10; i++)
        cout << "13 x " << setw(2) << i << " = " << setw(3) << 13 * i << endl;
    return 0;
}
Output
13 x  1 =  13
13 x  2 =  26
13 x  3 =  39
13 x  4 =  52
13 x  5 =  65
13 x  6 =  78
13 x  7 =  91
13 x  8 = 104
13 x  9 = 117
13 x 10 = 130

Pattern programs

Nested loops again: the outer loop chooses the row, the inner loops print the spaces and symbols on it.

22. Right triangle of stars

Task: Print a 5-row triangle of stars.

#include <iostream>
using namespace std;

int main() {
    for (int i = 1; i <= 5; i++) {
        for (int j = 1; j <= i; j++)
            cout << "* ";
        cout << endl;
    }
    return 0;
}
Output
* 
* * 
* * * 
* * * * 
* * * * * 

23. Pyramid of stars

Task: Print a centred pyramid using string(n, ch).

#include <iostream>
using namespace std;

int main() {
    int n = 5;
    for (int i = 1; i <= n; i++)
        cout << string(n - i, ' ') << string(2 * i - 1, '*') << endl;
    return 0;
}
Output
    *
   ***
  *****
 *******
*********

string(count, ch) builds a string of repeated characters, which replaces both inner loops.

24. Diamond of stars

Task: Print a diamond by drawing a pyramid and then an upside-down pyramid.

#include <iostream>
using namespace std;

int main() {
    int n = 4;
    for (int i = 1; i <= n; i++)
        cout << string(n - i, ' ') << string(2 * i - 1, '*') << endl;
    for (int i = n - 1; i >= 1; i--)
        cout << string(n - i, ' ') << string(2 * i - 1, '*') << endl;
    return 0;
}
Output
   *
  ***
 *****
*******
 *****
  ***
   *

25. Pascal's triangle

Task: Print the first 6 rows of Pascal's triangle.

#include <iostream>
using namespace std;

int main() {
    int rows = 6;
    for (int i = 0; i < rows; i++) {
        cout << string(rows - i - 1, ' ');
        int value = 1;
        for (int k = 0; k <= i; k++) {
            cout << value << " ";
            value = value * (i - k) / (k + 1);
        }
        cout << endl;
    }
    return 0;
}
Output
     1 
    1 1 
   1 2 1 
  1 3 3 1 
 1 4 6 4 1 
1 5 10 10 5 1 

Each next number in a row is the previous one times (i − k) / (k + 1), which avoids computing factorials.

Arrays and vectors

A plain array has a fixed size. A vector grows as you add to it, knows its own size, and works with the standard algorithms. Beginners should reach for vector by default.

26. Sum, average, largest and smallest in an array

Task: Process a fixed array of marks.

#include <iostream>
using namespace std;

int main() {
    int marks[] = {72, 88, 95, 61, 79, 84};
    int n = sizeof(marks) / sizeof(marks[0]);
    int sum = 0, hi = marks[0], lo = marks[0];
    for (int m : marks) {
        sum += m;
        if (m > hi) hi = m;
        if (m < lo) lo = m;
    }
    cout << "Sum " << sum << ", average " << (double)sum / n
         << ", highest " << hi << ", lowest " << lo << endl;
    return 0;
}
Output
Sum 479, average 79.8333, highest 95, lowest 61

27. Vector basics

Task: Create a vector, add and remove elements, and loop over it.

#include <iostream>
using namespace std;
#include <vector>

int main() {
    vector<int> v = {5, 10, 15};
    v.push_back(20);
    v.push_back(25);
    v.pop_back();
    v.insert(v.begin(), 0);
    cout << "Size: " << v.size() << endl;
    cout << "Elements:";
    for (int x : v) cout << " " << x;
    cout << endl;
    cout << "First " << v.front() << ", last " << v.back() << ", v[2] = " << v[2] << endl;
    return 0;
}
Output
Size: 5
Elements: 0 5 10 15 20
First 0, last 20, v[2] = 10

push_back() adds at the end and pop_back() removes from the end. v.at(i) is a safer version of v[i] that checks the index.

28. Reverse a vector

Task: Reverse a vector by hand and with std::reverse.

#include <iostream>
using namespace std;
#include <vector>
#include <algorithm>

int main() {
    vector<int> v = {1, 2, 3, 4, 5, 6, 7};
    for (size_t i = 0, j = v.size() - 1; i < j; i++, j--)
        swap(v[i], v[j]);
    for (int x : v) cout << x << " ";
    cout << endl;
    reverse(v.begin(), v.end());
    for (int x : v) cout << x << " ";
    cout << endl;
    return 0;
}
Output
7 6 5 4 3 2 1 
1 2 3 4 5 6 7 

29. Linear search in a vector

Task: Find the position of a value, by hand and with std::find.

#include <iostream>
using namespace std;
#include <vector>
#include <algorithm>

int main() {
    vector<int> v = {14, 3, 27, 8, 41, 19};
    int key = 41;
    for (size_t i = 0; i < v.size(); i++)
        if (v[i] == key) cout << key << " found at index " << i << endl;
    auto it = find(v.begin(), v.end(), 99);
    cout << "99 " << (it == v.end() ? "not found" : "found") << endl;
    return 0;
}
Output
41 found at index 4
99 not found

find() returns v.end() when the value is not there. Comparing with end() is how the standard library says "not found".

30. Bubble sort

Task: Sort a vector with bubble sort, stopping early if a pass makes no swaps.

#include <iostream>
using namespace std;
#include <vector>

int main() {
    vector<int> v = {29, 10, 14, 37, 13, 5};
    int passes = 0;
    for (size_t i = 0; i < v.size() - 1; i++) {
        bool swapped = false;
        for (size_t j = 0; j < v.size() - 1 - i; j++)
            if (v[j] > v[j + 1]) {
                swap(v[j], v[j + 1]);
                swapped = true;
            }
        passes++;
        if (!swapped) break;
    }
    for (int x : v) cout << x << " ";
    cout << "\nPasses: " << passes << endl;
    return 0;
}
Output
5 10 13 14 29 37 
Passes: 5

Task: Search a sorted vector by halving the range.

#include <iostream>
using namespace std;
#include <vector>

int binarySearch(const vector<int>& v, int key) {
    int low = 0, high = v.size() - 1;
    while (low <= high) {
        int mid = low + (high - low) / 2;
        if (v[mid] == key) return mid;
        if (v[mid] < key) low = mid + 1;
        else high = mid - 1;
    }
    return -1;
}

int main() {
    vector<int> v = {2, 5, 8, 12, 16, 23, 38, 56, 72, 91};
    cout << "23 at index " << binarySearch(v, 23) << endl;
    cout << "40 at index " << binarySearch(v, 40) << endl;
    return 0;
}
Output
23 at index 5
40 at index -1

low + (high - low) / 2 gives the same middle as (low + high) / 2 but cannot overflow for huge arrays. −1 means not found.

32. Matrix multiplication with 2D vectors

Task: Multiply two 2 by 2 matrices stored as vectors of vectors.

#include <iostream>
using namespace std;
#include <vector>

int main() {
    vector<vector<int>> a = {{1, 2}, {3, 4}};
    vector<vector<int>> b = {{5, 6}, {7, 8}};
    vector<vector<int>> c(2, vector<int>(2, 0));
    for (int i = 0; i < 2; i++)
        for (int j = 0; j < 2; j++)
            for (int k = 0; k < 2; k++)
                c[i][j] += a[i][k] * b[k][j];
    for (auto& row : c) {
        for (int x : row) cout << x << " ";
        cout << endl;
    }
    return 0;
}
Output
19 22 
43 50 

Strings

The C++ string class does the memory work for you: join with +, compare with ==, and ask for .size().

33. String basics

Task: Join, measure, slice and search strings.

#include <iostream>
using namespace std;
#include <string>

int main() {
    string first = "Modern", second = "Coders";
    string full = first + " Age " + second;
    cout << full << endl;
    cout << "Length: " << full.size() << endl;
    cout << "substr(7, 3): " << full.substr(7, 3) << endl;
    cout << "find(\"Coders\"): " << full.find("Coders") << endl;
    cout << "First char: " << full[0] << ", last char: " << full.back() << endl;
    return 0;
}
Output
Modern Age Coders
Length: 17
substr(7, 3): Age
find("Coders"): 11
First char: M, last char: s

substr(start, length) takes a starting index and a count, not an end index.

34. Palindrome string

Task: Check palindromes, ignoring case and spaces.

#include <iostream>
using namespace std;
#include <string>
#include <algorithm>
#include <cctype>

bool isPalindrome(string s) {
    string clean;
    for (char ch : s)
        if (isalpha(ch)) clean += tolower(ch);
    string rev(clean.rbegin(), clean.rend());
    return clean == rev;
}

int main() {
    for (string s : {"Madam", "Was it a car or a cat I saw", "Programming"})
        cout << s << ": " << (isPalindrome(s) ? "palindrome" : "not a palindrome") << endl;
    return 0;
}
Output
Madam: palindrome
Was it a car or a cat I saw: palindrome
Programming: not a palindrome

35. Count vowels, consonants and words

Task: Count the vowels, consonants and words in a sentence.

#include <iostream>
using namespace std;
#include <string>
#include <sstream>
#include <cctype>

int main() {
    string s = "Practice makes code better";
    int v = 0, c = 0, words = 0;
    for (char ch : s) {
        char l = tolower(ch);
        if (l == 'a' || l == 'e' || l == 'i' || l == 'o' || l == 'u') v++;
        else if (isalpha(l)) c++;
    }
    stringstream ss(s);
    string w;
    while (ss >> w) words++;
    cout << "Vowels " << v << ", consonants " << c << ", words " << words << endl;
    return 0;
}
Output
Vowels 9, consonants 14, words 4

A stringstream reads a string the way cin reads the keyboard, one word at a time, which makes word counting easy.

36. Read a full line of text

Task: Read a name with spaces using getline() and greet the user.

#include <iostream>
using namespace std;
#include <string>

int main() {
    string name;
    int age;
    cout << "Your full name: ";
    getline(cin, name);
    cout << "Your age: ";
    cin >> age;
    cout << "Hello " << name << ", in 10 years you will be " << age + 10 << endl;
    return 0;
}
Output (typed input included)
Your full name: Ira Malhotra
Your age: 15
Hello Ira Malhotra, in 10 years you will be 25

cin >> name would stop at the first space and keep only "Ira". getline() reads the whole line.

37. Change case and reverse words

Task: Convert a sentence to uppercase and print its words in reverse order.

#include <iostream>
using namespace std;
#include <string>
#include <vector>
#include <sstream>
#include <cctype>

int main() {
    string s = "learn one thing well";
    string up = s;
    for (char& ch : up) ch = toupper(ch);
    cout << up << endl;
    stringstream ss(s);
    vector<string> words;
    string w;
    while (ss >> w) words.push_back(w);
    for (int i = words.size() - 1; i >= 0; i--)
        cout << words[i] << (i ? " " : "\n");
    return 0;
}
Output
LEARN ONE THING WELL
well thing one learn

for (char& ch : up) uses a reference, so changing ch changes the string itself.

Functions, references and recursion

How C++ passes values, references and overloaded functions, and functions that call themselves.

38. Pass by value vs pass by reference

Task: Show that a reference parameter changes the caller's variable and a value parameter does not.

#include <iostream>
using namespace std;

void byValue(int x) { x = x * 10; }
void byReference(int& x) { x = x * 10; }

int main() {
    int a = 7, b = 7;
    byValue(a);
    byReference(b);
    cout << "after byValue: a = " << a << endl;
    cout << "after byReference: b = " << b << endl;
    return 0;
}
Output
after byValue: a = 7
after byReference: b = 70

The & in int& x makes x another name for the caller's variable. In C you would need a pointer for this; C++ references make it simpler.

39. Function overloading

Task: Write three area() functions with different parameters.

#include <iostream>
using namespace std;

const double PI = 3.14159;

double area(double r) { return PI * r * r; }            // circle
int area(int l, int w) { return l * w; }                // rectangle
double area(double b, double h, bool) { return 0.5 * b * h; }  // triangle

int main() {
    cout << "Circle r = 2: " << area(2.0) << endl;
    cout << "Rectangle 4 x 6: " << area(4, 6) << endl;
    cout << "Triangle b = 10, h = 3: " << area(10.0, 3.0, true) << endl;
    return 0;
}
Output
Circle r = 2: 12.5664
Rectangle 4 x 6: 24
Triangle b = 10, h = 3: 15

C++ picks the right function from the number and types of the arguments. (The unnamed bool only exists to give the triangle version a different parameter list.)

40. Default arguments

Task: Give a function default values for its later parameters.

#include <iostream>
using namespace std;

double compound(double principal, double rate = 5.0, int years = 1) {
    double amount = principal;
    for (int i = 0; i < years; i++)
        amount *= 1 + rate / 100;
    return amount;
}

int main() {
    cout << compound(1000) << endl;          // 5%, 1 year
    cout << compound(1000, 10) << endl;      // 10%, 1 year
    cout << compound(1000, 10, 3) << endl;   // 10%, 3 years
    return 0;
}
Output
1050
1100
1331

41. Recursion: factorial, power and sum of digits

Task: Solve three small problems with recursive functions.

#include <iostream>
using namespace std;

long long factorial(int n) { return n <= 1 ? 1 : n * factorial(n - 1); }
long long power(int b, int e) { return e == 0 ? 1 : b * power(b, e - 1); }
int digitSum(int n) { return n < 10 ? n : n % 10 + digitSum(n / 10); }

int main() {
    cout << "factorial(12) = " << factorial(12) << endl;
    cout << "power(2, 20) = " << power(2, 20) << endl;
    cout << "digitSum(98765) = " << digitSum(98765) << endl;
    return 0;
}
Output
factorial(12) = 479001600
power(2, 20) = 1048576
digitSum(98765) = 35

Each function has a base case (n <= 1, e == 0, n < 10) and a call on a smaller problem. Spot those two parts and every recursive function becomes readable.

42. Tower of Hanoi

Task: Print the moves to shift 3 discs from peg A to peg C.

#include <iostream>
using namespace std;

int moves = 0;

void hanoi(int n, char from, char to, char via) {
    if (n == 0) return;
    hanoi(n - 1, from, via, to);
    cout << "Move disc " << n << " from " << from << " to " << to << endl;
    moves++;
    hanoi(n - 1, via, to, from);
}

int main() {
    hanoi(3, 'A', 'C', 'B');
    cout << "Total moves: " << moves << endl;
    return 0;
}
Output
Move disc 1 from A to C
Move disc 2 from A to B
Move disc 1 from C to B
Move disc 3 from A to C
Move disc 1 from B to A
Move disc 2 from B to C
Move disc 1 from A to C
Total moves: 7

n discs always take 2n − 1 moves, so 3 discs take 7.

Classes and objects (OOP)

The idea C++ is known for: bundle data and the functions that work on it into a class, then create objects from it.

43. A first class: Rectangle

Task: Write a class with private data, a constructor and member functions.

#include <iostream>
using namespace std;

class Rectangle {
    double length, width;          // private by default
public:
    Rectangle(double l, double w) : length(l), width(w) {}
    double area() const { return length * width; }
    double perimeter() const { return 2 * (length + width); }
};

int main() {
    Rectangle r(8, 3.5);
    cout << "Area: " << r.area() << endl;
    cout << "Perimeter: " << r.perimeter() << endl;
    return 0;
}
Output
Area: 28
Perimeter: 23

Members of a class are private unless you say public:, so code outside the class cannot change length directly. That is encapsulation.

A class as a blueprint: the Rectangle class with private length and width and public area and perimeter functions, and an object r created from it with length 8 and width 3.5, giving area 28
A class is the blueprint, an object is the thing built from it.

44. Bank account class with validation

Task: Model a bank account that refuses invalid deposits and withdrawals.

#include <iostream>
using namespace std;
#include <string>

class BankAccount {
    string owner;
    double balance;
public:
    BankAccount(string name, double opening) : owner(name), balance(opening) {}
    void deposit(double amt) {
        if (amt <= 0) { cout << "Deposit must be positive" << endl; return; }
        balance += amt;
        cout << "Deposited " << amt << ", balance " << balance << endl;
    }
    void withdraw(double amt) {
        if (amt > balance) { cout << "Insufficient balance" << endl; return; }
        balance -= amt;
        cout << "Withdrew " << amt << ", balance " << balance << endl;
    }
};

int main() {
    BankAccount acc("Kavya", 500);
    acc.deposit(250);
    acc.withdraw(1000);
    acc.withdraw(300);
    acc.deposit(-20);
    return 0;
}
Output
Deposited 250, balance 750
Insufficient balance
Withdrew 300, balance 450
Deposit must be positive

Because balance is private, the only way to change it is through deposit() and withdraw(), which check every request first.

45. Constructors and destructors

Task: Show when a constructor and a destructor run.

#include <iostream>
using namespace std;
#include <string>

class Tracker {
    string name;
public:
    Tracker(string n) : name(n) { cout << "Constructor: " << name << endl; }
    ~Tracker() { cout << "Destructor: " << name << endl; }
};

int main() {
    Tracker a("first");
    {
        Tracker b("inner");
        cout << "Inside the block" << endl;
    }
    cout << "Back in main" << endl;
    return 0;
}
Output
Constructor: first
Constructor: inner
Inside the block
Destructor: inner
Back in main
Destructor: first

b is destroyed as soon as its block ends; a lasts until main() finishes. Objects are destroyed in reverse order of creation.

46. Inheritance

Task: Create a Student class that inherits from a Person class.

#include <iostream>
using namespace std;
#include <string>

class Person {
protected:
    string name;
    int age;
public:
    Person(string n, int a) : name(n), age(a) {}
    void introduce() const { cout << "I am " << name << ", age " << age << endl; }
};

class Student : public Person {
    string school;
public:
    Student(string n, int a, string s) : Person(n, a), school(s) {}
    void study() const { cout << name << " studies at " << school << endl; }
};

int main() {
    Student s("Arjun", 16, "Green Valley School");
    s.introduce();      // inherited from Person
    s.study();          // Student's own function
    return 0;
}
Output
I am Arjun, age 16
Arjun studies at Green Valley School

protected members are hidden from outside code but visible to derived classes, which is why study() can use name.

47. Polymorphism with virtual functions

Task: Call the right area() for different shapes through a base-class pointer.

#include <iostream>
using namespace std;
#include <vector>
#include <memory>

class Shape {
public:
    virtual double area() const = 0;     // pure virtual: Shape is abstract
    virtual string name() const = 0;
    virtual ~Shape() = default;
};

class Circle : public Shape {
    double r;
public:
    Circle(double r) : r(r) {}
    double area() const override { return 3.14159 * r * r; }
    string name() const override { return "Circle"; }
};

class Square : public Shape {
    double s;
public:
    Square(double s) : s(s) {}
    double area() const override { return s * s; }
    string name() const override { return "Square"; }
};

int main() {
    vector<unique_ptr<Shape>> shapes;
    shapes.push_back(make_unique<Circle>(1.5));
    shapes.push_back(make_unique<Square>(4));
    for (const auto& sh : shapes)
        cout << sh->name() << " area: " << sh->area() << endl;
    return 0;
}
Output
Circle area: 7.06858
Square area: 16

The loop only knows it has Shape pointers, yet each object runs its own area(). That is runtime polymorphism, made possible by virtual. unique_ptr deletes each shape automatically.

48. Operator overloading

Task: Add two fractions with the + operator and print them with <<.

#include <iostream>
using namespace std;
#include <numeric>

class Fraction {
    int num, den;
public:
    Fraction(int n, int d) : num(n), den(d) {
        int g = gcd(num, den);
        num /= g; den /= g;
    }
    Fraction operator+(const Fraction& o) const {
        return Fraction(num * o.den + o.num * den, den * o.den);
    }
    friend ostream& operator<<(ostream& out, const Fraction& f) {
        return out << f.num << "/" << f.den;
    }
};

int main() {
    Fraction a(1, 4), b(1, 6);
    cout << a << " + " << b << " = " << a + b << endl;
    return 0;
}
Output
1/4 + 1/6 = 5/12

The constructor reduces every fraction with gcd(), so 10/24 becomes 5/12 automatically.

49. Function templates

Task: Write one function that works for any type.

#include <iostream>
using namespace std;
#include <string>

template <typename T>
T largest(T a, T b, T c) {
    T m = a;
    if (b > m) m = b;
    if (c > m) m = c;
    return m;
}

int main() {
    cout << largest(3, 9, 4) << endl;
    cout << largest(2.5, 1.5, 2.75) << endl;
    cout << largest(string("kiwi"), string("apple"), string("mango")) << endl;
    return 0;
}
Output
9
2.75
mango

The compiler writes a separate version of largest() for int, double and string. Strings compare alphabetically, so "mango" wins.

The standard library, exceptions and files

Ready-made tools that save you writing your own: sort, map, set, exceptions and file streams.

50. Sorting with std::sort

Task: Sort numbers ascending and descending, and sort words by length.

#include <iostream>
using namespace std;
#include <vector>
#include <algorithm>
#include <string>

int main() {
    vector<int> v = {42, 7, 19, 73, 3, 56};
    sort(v.begin(), v.end());
    for (int x : v) cout << x << " ";
    cout << endl;
    sort(v.begin(), v.end(), greater<int>());
    for (int x : v) cout << x << " ";
    cout << endl;
    vector<string> w = {"banana", "fig", "cherry", "kiwi"};
    stable_sort(w.begin(), w.end(), [](const string& a, const string& b) {
        return a.size() < b.size();
    });
    for (auto& s : w) cout << s << " ";
    cout << endl;
    return 0;
}
Output
3 7 19 42 56 73 
73 56 42 19 7 3 
fig kiwi banana cherry 

The third argument to sort() decides the order. The last one is a lambda, a small unnamed function written in place. We use stable_sort() there so words of equal length (banana and cherry) keep their original order on every compiler.

51. Word frequency with map

Task: Count how many times each word appears in a sentence.

#include <iostream>
using namespace std;
#include <map>
#include <sstream>
#include <string>

int main() {
    string text = "the cat and the dog and the bird";
    map<string, int> freq;
    stringstream ss(text);
    string w;
    while (ss >> w) freq[w]++;
    for (const auto& [word, count] : freq)
        cout << word << ": " << count << endl;
    return 0;
}
Output
and: 2
bird: 1
cat: 1
dog: 1
the: 3

freq[w]++ creates the entry with 0 the first time a word appears. A map keeps its keys sorted, so the words come out alphabetically.

52. Remove duplicates with set

Task: Keep only the unique values from a list.

#include <iostream>
using namespace std;
#include <set>
#include <vector>

int main() {
    vector<int> rolls = {4, 2, 6, 2, 4, 4, 1, 6, 3};
    set<int> unique(rolls.begin(), rolls.end());
    cout << "Unique values:";
    for (int x : unique) cout << " " << x;
    cout << "\nCount: " << unique.size() << endl;
    cout << "Contains 5? " << (unique.count(5) ? "yes" : "no") << endl;
    return 0;
}
Output
Unique values: 1 2 3 4 6
Count: 5
Contains 5? no

53. Exception handling

Task: Catch division by zero and an out-of-range index.

#include <iostream>
using namespace std;
#include <vector>
#include <stdexcept>

double safeDivide(double a, double b) {
    if (b == 0) throw runtime_error("division by zero");
    return a / b;
}

int main() {
    try {
        cout << safeDivide(10, 4) << endl;
        cout << safeDivide(1, 0) << endl;
    } catch (const runtime_error& e) {
        cout << "Error: " << e.what() << endl;
    }
    vector<int> v = {1, 2, 3};
    try {
        cout << v.at(5) << endl;
    } catch (const out_of_range& e) {
        cout << "Index error caught" << endl;
    }
    return 0;
}
Output
2.5
Error: division by zero
Index error caught

throw jumps straight to the matching catch, skipping the rest of the try block. v.at(5) throws out_of_range, where v[5] would silently read invalid memory.

54. Write and read a file with fstream

Task: Save student marks to a file, read them back and find the average.

#include <iostream>
using namespace std;
#include <fstream>
#include <string>

int main() {
    ofstream out("marks.txt");
    out << "Riya 88\nOmar 74\nLeela 93\n";
    out.close();

    ifstream in("marks.txt");
    string name;
    int mark, total = 0, count = 0;
    while (in >> name >> mark) {
        cout << name << " scored " << mark << endl;
        total += mark;
        count++;
    }
    cout << "Average: " << (double)total / count << endl;
    return 0;
}
Output
Riya scored 88
Omar scored 74
Leela scored 93
Average: 85

ofstream writes and ifstream reads, using the same << and >> as cout and cin. The loop stops when in >> name >> mark fails at the end of the file.

C programs vs C++ programs: what changes

Task C C++
Print printf("%d", x); cout << x;
Read input scanf("%d", &x); cin >> x;
Text char s[50]; and string.h string s; with +, ==, .size()
List of values fixed-size array vector<int> that grows
Change a caller's variable pointer: int *x reference: int& x
Group data and functions struct with data only class with data, functions and access control
Errors return codes exceptions: throw, try, catch

Common mistakes beginners make in C++

  • Mixing cin >> and getline(): after cin >> age, the newline is still waiting, so a following getline() returns an empty line. Call cin.ignore() in between.
  • Integer division: 7 / 2 is 3. Use 7.0 / 2 or a cast when you want 3.5.
  • Out-of-range indexes: v[10] on a 5-element vector is undefined behaviour. Use v.at(10) while learning; it throws an exception instead.
  • Forgetting the semicolon after a class: class A { ... }; needs that final semicolon.
  • Comparing signed and unsigned: v.size() is unsigned, so loop with size_t or the range-based for to avoid surprises (and warnings).
  • Missing headers: code that compiles on one compiler can fail on another if you rely on a header being included by accident. Include what you use: <vector>, <string>, <algorithm>.
💡

Change one thing, then predict

After a program works, change one value (the vector, the loop limit, the input) and predict the new output before running it. Being right twice in a row means you understand the program; being wrong shows you exactly which line to reread.

Practice list: C++ programs to try on your own

  1. Read 5 numbers into a vector and print them in sorted order without using sort().
  2. Count the uppercase letters, lowercase letters and digits in a string.
  3. Write a Student class with a name and three marks, and a function that returns the average.
  4. Add a Triangle class to the polymorphism program.
  5. Use a map to count how many times each letter appears in a word.
  6. Write a recursive function that reverses a string.
  7. Overload == for the Fraction class so 1/2 == 2/4 is true.
  8. Write a template function that returns the largest element of any vector.
  9. Read numbers from a file and write only the even ones to another file.
  10. Throw an exception from a BankAccount instead of printing a message, and catch it in main().

Which C++ programs to learn first

  • Complete beginner: programs 1 to 25 (basics, decisions, loops, patterns).
  • Next: programs 26 to 37 (arrays, vectors and strings).
  • Then: programs 38 to 49 (functions, recursion and classes).
  • Last: programs 50 to 54 (standard library, exceptions and files).

If recursion feels strange, our recursion guide traces each call step by step. Once vectors, sorting and searching feel easy, how to start learning data structures and algorithms shows where C++ is most often used next.

How we teach it

Our how we teach page describes how lessons run: students explain their thinking, trace a loop line by line until they can predict every step, and treat mistakes as data, not failures. With C++ that means predicting which constructor and destructor run before running the program, and reading a compiler error out loud before touching the code. Our C++ for beginners page explains the options, and the C++ course for teens and C++ course for kids build from programs like these to games and contest problems. The first class is free.

Frequently asked questions

Hello World, adding two numbers, swapping values, even or odd, largest of three numbers, leap year, factorial, Fibonacci, prime check, reversing a number, star patterns, array sum and average, string reversal and a first class such as Rectangle. All are on this page with their output.

Save it as a .cpp file, compile it with c++ or g++ (for example c++ -std=c++17 hello.cpp -o hello), then run the result (./hello on Mac or Linux, hello.exe on Windows). IDEs such as Code::Blocks and Visual Studio do both steps with one button.

No, you can start with C++ directly. C++ includes almost all of C, and its strings and vectors are easier for beginners than C's character arrays. Learning C first does help you understand pointers and memory, so either order works.

C++ adds classes and objects, references, function overloading, templates, exceptions and a large standard library (string, vector, map, set, sort). The table on this page shows the most common swaps, such as cout for printf and vector for fixed arrays.

In small learning programs it is fine and keeps the code short. In larger projects and header files, writing std:: in full avoids name clashes, so many teams avoid it there.

C++17 or newer. Every program here was compiled as C++17. A few use features (gcd, lcm and structured bindings) that older standards do not have.

It is widely used there, because it is fast and the standard library has sorting, maps, sets and many algorithms ready to use. Programs 26 to 32 and 50 to 52 are the foundation.

Open this page, press Ctrl+P or Cmd+P and choose Save as PDF. Every program and output prints in order.

Prefer to start with C? See our C programs for beginners, with the same topics in plain C.

Modern Age Coders Team

About Modern Age Coders Team

Expert educators making coding and maths clear for ages 6 to 67.

Keep exploring Modern Age Coders

More from the blog

Learn more

Free resources

From the blog

Start here

Ask Misti AI
Chat with us
Enroll Watch Class Priority Demo Enrol Book a Demo Watch Class WhatsApp Book demo today