C++ Programming Solutions

Practical code examples and solutions for all C++ concepts

Code Examples Solutions Practice

1. Introduction to C++, Basic Syntax and Structure

Hello World Program
hello.cpp
#include <iostream>
using namespace std;

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

The most basic C++ program that outputs "Hello, World!" to the console.

Basic Program Structure
structure.cpp
#include <iostream>  // Header file
using namespace std; // Standard namespace

// Main function - program entry point
int main() {
    // Variable declaration
    int number = 10;
    
    // Output statement
    cout << "Number is: " << number << endl;
    
    // Return statement
    return 0;
}

Shows the basic structure of a C++ program with comments explaining each part.

2. Variables and Data Types, Constants and Literals

Data Types Example
datatypes.cpp
#include <iostream>
using namespace std;

int main() {
    // Integer types
    int age = 25;
    short s = 32767;
    long l = 100000L;
    
    // Floating point types
    float price = 19.99f;
    double pi = 3.14159;
    
    // Character type
    char grade = 'A';
    
    // Boolean type
    bool isValid = true;
    
    // Output values
    cout << "Age: " << age << endl;
    cout << "Price: " << price << endl;
    cout << "Grade: " << grade << endl;
    cout << "Is Valid: " << boolalpha << isValid << endl;
    
    return 0;
}

Demonstrates different data types available in C++.

Constants and Literals
constants.cpp
#include <iostream>
using namespace std;

// Define a constant using #define
#define PI 3.14159

// Define a constant using const keyword
const int MAX_SIZE = 100;

int main() {
    // Literals examples
    int decimal = 100;        // Decimal literal
    int octal = 0144;         // Octal literal
    int hex = 0x64;           // Hexadecimal literal
    
    float f1 = 3.14f;         // Float literal
    double d1 = 3.14;         // Double literal
    
    char ch = 'A';            // Character literal
    char str[] = "Hello";     // String literal
    
    bool flag = true;         // Boolean literal
    
    cout << "PI: " << PI << endl;
    cout << "MAX_SIZE: " << MAX_SIZE << endl;
    cout << "Hexadecimal 0x64: " << hex << endl;
    
    return 0;
}

Shows how to define constants and use different types of literals in C++.

3. Input and Output (I/O), Operators

Basic I/O Operations
io.cpp
#include <iostream>
using namespace std;

int main() {
    int age;
    float height;
    string name;
    
    // Getting input from user
    cout << "Enter your name: ";
    getline(cin, name);
    
    cout << "Enter your age: ";
    cin >> age;
    
    cout << "Enter your height (in meters): ";
    cin >> height;
    
    // Displaying output
    cout << "\n--- User Information ---" << endl;
    cout << "Name: " << name << endl;
    cout << "Age: " << age << endl;
    cout << "Height: " << height << " meters" << endl;
    
    return 0;
}

Demonstrates basic input and output operations in C++.

Operators in C++
operators.cpp
#include <iostream>
using namespace std;

int main() {
    int a = 10, b = 3;
    
    // Arithmetic operators
    cout << "a + b = " << (a + b) << endl;
    cout << "a - b = " << (a - b) << endl;
    cout << "a * b = " << (a * b) << endl;
    cout << "a / b = " << (a / b) << endl;
    cout << "a % b = " << (a % b) << endl;
    
    // Relational operators
    cout << "a == b: " << (a == b) << endl;
    cout << "a != b: " << (a != b) << endl;
    cout << "a > b: " << (a > b) << endl;
    
    // Logical operators
    bool x = true, y = false;
    cout << "x && y: " << (x && y) << endl;
    cout << "x || y: " << (x || y) << endl;
    cout << "!x: " << (!x) << endl;
    
    // Assignment operators
    int c = a;
    c += b;
    cout << "c += b: " << c << endl;
    
    // Increment/Decrement
    cout << "a++: " << a++ << endl; // Post-increment
    cout << "++a: " << ++a << endl; // Pre-increment
    
    return 0;
}

Shows different types of operators available in C++.

4. Conditional Control Statements

If-Else Statements
ifelse.cpp
#include <iostream>
using namespace std;

int main() {
    int number;
    
    cout << "Enter a number: ";
    cin >> number;
    
    // Simple if statement
    if (number > 0) {
        cout << "The number is positive." << endl;
    }
    
    // If-else statement
    if (number % 2 == 0) {
        cout << "The number is even." << endl;
    } else {
        cout << "The number is odd." << endl;
    }
    
    // If-else if ladder
    if (number > 0) {
        cout << "Positive number" << endl;
    } else if (number < 0) {
        cout << "Negative number" << endl;
    } else {
        cout << "Zero" << endl;
    }
    
    return 0;
}

Demonstrates different forms of if-else conditional statements.

Switch Statement
switch.cpp
#include <iostream>
using namespace std;

int main() {
    char grade;
    
    cout << "Enter your grade (A, B, C, D, F): ";
    cin >> grade;
    
    switch (grade) {
        case 'A':
        case 'a':
            cout << "Excellent!" << endl;
            break;
        case 'B':
        case 'b':
            cout << "Well done!" << endl;
            break;
        case 'C':
        case 'c':
            cout << "Good job!" << endl;
            break;
        case 'D':
        case 'd':
            cout << "You passed, but could do better." << endl;
            break;
        case 'F':
        case 'f':
            cout << "Sorry, you failed." << endl;
            break;
        default:
            cout << "Invalid grade entered." << endl;
    }
    
    return 0;
}

Shows how to use switch statements for multiple conditional branches.

5. Loops

For Loop
forloop.cpp
#include <iostream>
using namespace std;

int main() {
    // Basic for loop
    cout << "Counting from 1 to 5:" << endl;
    for (int i = 1; i <= 5; i++) {
        cout << i << " ";
    }
    cout << endl << endl;
    
    // Nested for loop (multiplication table)
    cout << "Multiplication Table (1-5):" << endl;
    for (int i = 1; i <= 5; i++) {
        for (int j = 1; j <= 5; j++) {
            cout << i * j << "\t";
        }
        cout << endl;
    }
    cout << endl;
    
    // For loop with array
    int numbers[] = {10, 20, 30, 40, 50};
    cout << "Array elements: ";
    for (int i = 0; i < 5; i++) {
        cout << numbers[i] << " ";
    }
    cout << endl;
    
    return 0;
}

Demonstrates different uses of for loops in C++.

While and Do-While Loops
whileloop.cpp
#include <iostream>
using namespace std;

int main() {
    // While loop example
    cout << "While loop - counting from 1 to 5:" << endl;
    int i = 1;
    while (i <= 5) {
        cout << i << " ";
        i++;
    }
    cout << endl << endl;
    
    // Do-while loop example
    cout << "Do-while loop - counting from 1 to 5:" << endl;
    int j = 1;
    do {
        cout << j << " ";
        j++;
    } while (j <= 5);
    cout << endl << endl;
    
    // Practical example: Sum of numbers until 0 is entered
    int number, sum = 0;
    cout << "Enter numbers to sum (enter 0 to stop):" << endl;
    
    while (true) {
        cin >> number;
        if (number == 0) {
            break;
        }
        sum += number;
    }
    
    cout << "Sum of entered numbers: " << sum << endl;
    
    return 0;
}

Shows how to use while and do-while loops in C++.

6. Arrays

Single Dimensional Arrays
arrays.cpp
#include <iostream>
using namespace std;

int main() {
    // Array declaration and initialization
    int numbers[5] = {10, 20, 30, 40, 50};
    
    // Accessing array elements
    cout << "First element: " << numbers[0] << endl;
    cout << "Third element: " << numbers[2] << endl;
    
    // Modifying array elements
    numbers[1] = 25;
    cout << "Modified second element: " << numbers[1] << endl;
    
    // Looping through an array
    cout << "All elements: ";
    for (int i = 0; i < 5; i++) {
        cout << numbers[i] << " ";
    }
    cout << endl;
    
    // Calculating sum of array elements
    int sum = 0;
    for (int i = 0; i < 5; i++) {
        sum += numbers[i];
    }
    cout << "Sum of elements: " << sum << endl;
    
    // Finding maximum element
    int max = numbers[0];
    for (int i = 1; i < 5; i++) {
        if (numbers[i] > max) {
            max = numbers[i];
        }
    }
    cout << "Maximum element: " << max << endl;
    
    return 0;
}

Demonstrates how to work with single dimensional arrays in C++.

Multi-dimensional Arrays
multidimarray.cpp
#include <iostream>
using namespace std;

int main() {
    // 2D array declaration and initialization
    int matrix[3][3] = {
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9}
    };
    
    // Accessing and displaying 2D array
    cout << "2D Array elements:" << endl;
    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 3; j++) {
            cout << matrix[i][j] << " ";
        }
        cout << endl;
    }
    
    // Sum of all elements in 2D array
    int total = 0;
    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 3; j++) {
            total += matrix[i][j];
        }
    }
    cout << "Sum of all elements: " << total << endl;
    
    // 3D array example
    int threeD[2][2][2] = {
        {{1, 2}, {3, 4}},
        {{5, 6}, {7, 8}}
    };
    
    cout << "3D Array elements:" << endl;
    for (int i = 0; i < 2; i++) {
        for (int j = 0; j < 2; j++) {
            for (int k = 0; k < 2; k++) {
                cout << threeD[i][j][k] << " ";
            }
            cout << endl;
        }
        cout << endl;
    }
    
    return 0;
}

Shows how to work with multi-dimensional arrays in C++.

7. Strings

String Operations
strings.cpp
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;

int main() {
    // String initialization
    string s1 = "Hello";
    string s2(" World!");
    string s3 = s1 + s2;
    
    cout << "Concatenated string: " << s3 << endl;
    cout << "Length: " << s3.length() << endl;
    cout << "First character: " << s3[0] << endl;
    cout << "Substring: " << s3.substr(6, 5) << endl;
    
    // Finding substrings
    size_t pos = s3.find("World");
    if (pos != string::npos) {
        cout << "'World' found at position: " << pos << endl;
    }
    
    // String modification
    s3.replace(6, 5, "C++");
    cout << "After replacement: " << s3 << endl;
    
    // String comparison
    string s4 = "Hello World!";
    if (s3 == s4) {
        cout << "Strings are equal" << endl;
    } else {
        cout << "Strings are different" << endl;
    }
    
    // Converting case
    string s5 = "C++ Programming";
    transform(s5.begin(), s5.end(), s5.begin(), ::toupper);
    cout << "Uppercase: " << s5 << endl;
    
    transform(s5.begin(), s5.end(), s5.begin(), ::tolower);
    cout << "Lowercase: " << s5 << endl;
    
    return 0;
}

Demonstrates various string operations in C++.

String Input and Manipulation
string_manipulation.cpp
#include <iostream>
#include <string>
#include <sstream>
using namespace std;

int main() {
    // Different ways to read strings
    string fullName, firstName, lastName;
    
    cout << "Enter your full name: ";
    getline(cin, fullName);
    cout << "Full Name: " << fullName << endl;
    
    // Using string stream
    stringstream ss(fullName);
    ss >> firstName >> lastName;
    cout << "First Name: " << firstName << endl;
    cout << "Last Name: " << lastName << endl;
    
    // String manipulation
    string text = "   C++ Programming Language   ";
    cout << "Original: '" << text << "'" << endl;
    
    // Remove whitespace
    size_t start = text.find_first_not_of(" ");
    size_t end = text.find_last_not_of(" ");
    string trimmed = text.substr(start, end - start + 1);
    cout << "Trimmed: '" << trimmed << "'" << endl;
    
    // Erase and insert
    text.erase(0, 3); // Remove first 3 characters
    cout << "After erase: '" << text << "'" << endl;
    
    text.insert(0, "C++ ");
    cout << "After insert: '" << text << "'" << endl;
    
    // Numeric conversion
    string numStr = "1234";
    int number = stoi(numStr);
    cout << "String to integer: " << number * 2 << endl;
    
    number = 5678;
    numStr = to_string(number);
    cout << "Integer to string: " << numStr + " appended" << endl;
    
    return 0;
}

Shows various string input methods and manipulation techniques.

8. Functions and Recursion

Function Basics
functions.cpp
#include <iostream>
using namespace std;

// Function declaration
int add(int a, int b);
void printMessage(string message = "Hello World!");
double calculateCircleArea(double radius);

// Function definition
int add(int a, int b) {
    return a + b;
}

void printMessage(string message) {
    cout << message << endl;
}

double calculateCircleArea(double radius) {
    const double PI = 3.14159;
    return PI * radius * radius;
}

// Function overloading
int multiply(int a, int b) {
    return a * b;
}

double multiply(double a, double b) {
    return a * b;
}

// Inline function
inline int square(int x) {
    return x * x;
}

int main() {
    // Calling functions
    int sum = add(5, 3);
    cout << "5 + 3 = " << sum << endl;
    
    printMessage();
    printMessage("Custom message");
    
    double area = calculateCircleArea(5.0);
    cout << "Area of circle with radius 5: " << area << endl;
    
    // Function overloading
    cout << "Multiply integers: " << multiply(4, 5) << endl;
    cout << "Multiply doubles: " << multiply(4.5, 2.5) << endl;
    
    // Inline function
    cout << "Square of 7: " << square(7) << endl;
    
    return 0;
}

Demonstrates function declaration, definition, overloading, and inline functions.

Recursion Examples
recursion.cpp
#include <iostream>
using namespace std;

// Factorial using recursion
unsigned long long factorial(int n) {
    if (n <= 1) return 1;
    return n * factorial(n - 1);
}

// Fibonacci series using recursion
int fibonacci(int n) {
    if (n <= 1) return n;
    return fibonacci(n - 1) + fibonacci(n - 2);
}

// GCD using recursion (Euclidean algorithm)
int gcd(int a, int b) {
    if (b == 0) return a;
    return gcd(b, a % b);
}

// Tower of Hanoi using recursion
void towerOfHanoi(int n, char from_rod, char to_rod, char aux_rod) {
    if (n == 1) {
        cout << "Move disk 1 from rod " << from_rod << " to rod " << to_rod << endl;
        return;
    }
    towerOfHanoi(n - 1, from_rod, aux_rod, to_rod);
    cout << "Move disk " << n << " from rod " << from_rod << " to rod " << to_rod << endl;
    towerOfHanoi(n - 1, aux_rod, to_rod, from_rod);
}

// Recursive function to calculate power
double power(double base, int exponent) {
    if (exponent == 0) return 1;
    if (exponent > 0) return base * power(base, exponent - 1);
    return 1 / base * power(base, exponent + 1);
}

int main() {
    // Factorial
    int num = 5;
    cout << "Factorial of " << num << " is " << factorial(num) << endl;
    
    // Fibonacci
    cout << "Fibonacci series up to 10 terms: ";
    for (int i = 0; i < 10; i++) {
        cout << fibonacci(i) << " ";
    }
    cout << endl;
    
    // GCD
    int a = 56, b = 98;
    cout << "GCD of " << a << " and " << b << " is " << gcd(a, b) << endl;
    
    // Power
    cout << "2^5 = " << power(2, 5) << endl;
    cout << "2^-3 = " << power(2, -3) << endl;
    
    // Tower of Hanoi
    cout << "Tower of Hanoi with 3 disks:" << endl;
    towerOfHanoi(3, 'A', 'C', 'B');
    
    return 0;
}

Shows various examples of recursion including factorial, Fibonacci, GCD, and Tower of Hanoi.

9. Pointers and Dynamic Memory

Pointer Basics
pointers.cpp
#include <iostream>
using namespace std;

int main() {
    // Basic pointers
    int num = 10;
    int *ptr = #
    
    cout << "Value of num: " << num << endl;
    cout << "Address of num: " << &num << endl;
    cout << "Value of ptr: " << ptr << endl;
    cout << "Value pointed by ptr: " << *ptr << endl;
    
    // Pointer arithmetic
    int arr[] = {10, 20, 30, 40, 50};
    int *arrPtr = arr;
    
    cout << "\nArray elements using pointer:" << endl;
    for (int i = 0; i < 5; i++) {
        cout << "*(arrPtr + " << i << ") = " << *(arrPtr + i) << endl;
    }
    
    // Pointer to pointer
    int **pptr = &ptr;
    cout << "\nValue of pptr: " << pptr << endl;
    cout << "Value pointed by pptr: " << *pptr << endl;
    cout << "Value pointed by *pptr: " << **pptr << endl;
    
    // Pointers and functions
    void swap(int*, int*);
    int x = 5, y = 10;
    cout << "\nBefore swap: x = " << x << ", y = " << y << endl;
    swap(&x, &y);
    cout << "After swap: x = " << x << ", y = " << y << endl;
    
    // Pointers and arrays
    char name[] = "C++";
    char *charPtr = name;
    
    cout << "\nString using pointer: ";
    while (*charPtr != '\0') {
        cout << *charPtr;
        charPtr++;
    }
    cout << endl;
    
    return 0;
}

void swap(int *a, int *b) {
    int temp = *a;
    *a = *b;
    *b = temp;
}

Demonstrates pointer basics, arithmetic, and usage with arrays and functions.

Dynamic Memory Allocation
dynamic_memory.cpp
#include <iostream>
using namespace std;

int main() {
    // Dynamic memory allocation for single variable
    int *p = new int;
    *p = 25;
    cout << "Dynamically allocated integer: " << *p << endl;
    delete p;
    
    // Dynamic memory allocation for array
    int size;
    cout << "Enter array size: ";
    cin >> size;
    
    int *arr = new int[size];
    
    cout << "Enter " << size << " integers:" << endl;
    for (int i = 0; i < size; i++) {
        cin >> arr[i];
    }
    
    cout << "You entered: ";
    for (int i = 0; i < size; i++) {
        cout << arr[i] << " ";
    }
    cout << endl;
    
    delete[] arr;
    
    // Dynamic memory for 2D array
    int rows, cols;
    cout << "\nEnter number of rows and columns: ";
    cin >> rows >> cols;
    
    // Allocate memory for 2D array
    int **matrix = new int*[rows];
    for (int i = 0; i < rows; i++) {
        matrix[i] = new int[cols];
    }
    
    // Initialize matrix
    int value = 1;
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            matrix[i][j] = value++;
        }
    }
    
    // Display matrix
    cout << "2D Matrix:" << endl;
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            cout << matrix[i][j] << "\t";
        }
        cout << endl;
    }
    
    // Free memory
    for (int i = 0; i < rows; i++) {
        delete[] matrix[i];
    }
    delete[] matrix;
    
    // Dynamic memory with objects
    class Rectangle {
    public:
        double length, width;
        Rectangle(double l, double w) : length(l), width(w) {}
        double area() { return length * width; }
    };
    
    Rectangle *rect = new Rectangle(10.5, 5.5);
    cout << "\nArea of rectangle: " << rect->area() << endl;
    delete rect;
    
    return 0;
}

Shows dynamic memory allocation for variables, arrays, and objects using new and delete operators.

10. Object-Oriented Programming (OOP)

Classes and Objects
classes.cpp
#include <iostream>
#include <string>
using namespace std;

// Class definition
class Car {
private:
    string brand;
    string model;
    int year;
    
public:
    // Constructor
    Car(string b, string m, int y) : brand(b), model(m), year(y) {}
    
    // Default constructor
    Car() : brand("Unknown"), model("Unknown"), year(0) {}
    
    // Copy constructor
    Car(const Car &other) {
        brand = other.brand;
        model = other.model;
        year = other.year;
    }
    
    // Destructor
    ~Car() {
        cout << "Car object destroyed: " << brand << " " << model << endl;
    }
    
    // Member functions
    void displayInfo() {
        cout << year << " " << brand << " " << model << endl;
    }
    
    void setBrand(string b) { brand = b; }
    string getBrand() const { return brand; }
    
    void setModel(string m) { model = m; }
    string getModel() const { return model; }
    
    void setYear(int y) { year = y; }
    int getYear() const { return year; }
};

// Inheritance example
class ElectricCar : public Car {
private:
    double batteryCapacity;
    
public:
    ElectricCar(string b, string m, int y, double capacity) 
        : Car(b, m, y), batteryCapacity(capacity) {}
    
    void displayInfo() {
        Car::displayInfo();
        cout << "Battery Capacity: " << batteryCapacity << " kWh" << endl;
    }
    
    double getBatteryCapacity() const { return batteryCapacity; }
};

int main() {
    // Creating objects
    Car car1("Toyota", "Camry", 2022);
    Car car2; // Using default constructor
    
    car1.displayInfo();
    car2.displayInfo();
    
    // Using setter and getter
    car2.setBrand("Honda");
    car2.setModel("Civic");
    car2.setYear(2023);
    cout << "Car2 brand: " << car2.getBrand() << endl;
    
    // Copy constructor
    Car car3 = car1;
    cout << "Copied car: ";
    car3.displayInfo();
    
    // Inheritance
    ElectricCar eCar("Tesla", "Model S", 2023, 100.0);
    cout << "\nElectric Car: ";
    eCar.displayInfo();
    
    // Polymorphism
    Car *carPtr = &eCar;
    cout << "Using base class pointer: ";
    carPtr->displayInfo();
    
    return 0;
}

Demonstrates classes, objects, constructors, destructors, and basic inheritance.

Polymorphism and Advanced OOP
polymorphism.cpp
#include <iostream>
#include <string>
using namespace std;

// Abstract base class
class Shape {
protected:
    string name;
    
public:
    Shape(string n) : name(n) {}
    virtual ~Shape() {}
    
    // Pure virtual function (makes class abstract)
    virtual double area() const = 0;
    virtual double perimeter() const = 0;
    
    // Virtual function with implementation
    virtual void display() const {
        cout << "Shape: " << name << endl;
    }
    
    string getName() const { return name; }
};

// Derived class: Rectangle
class Rectangle : public Shape {
private:
    double length, width;
    
public:
    Rectangle(double l, double w, string n = "Rectangle") 
        : Shape(n), length(l), width(w) {}
    
    double area() const override {
        return length * width;
    }
    
    double perimeter() const override {
        return 2 * (length + width);
    }
    
    void display() const override {
        cout << "Rectangle - Length: " << length 
             << ", Width: " << width << endl;
        cout << "Area: " << area() 
             << ", Perimeter: " << perimeter() << endl;
    }
};

// Derived class: Circle
class Circle : public Shape {
private:
    double radius;
    const double PI = 3.14159;
    
public:
    Circle(double r, string n = "Circle") 
        : Shape(n), radius(r) {}
    
    double area() const override {
        return PI * radius * radius;
    }
    
    double perimeter() const override {
        return 2 * PI * radius;
    }
    
    void display() const override {
        cout << "Circle - Radius: " << radius << endl;
        cout << "Area: " << area() 
             << ", Circumference: " << perimeter() << endl;
    }
};

// Friend function example
class Box {
private:
    double width;
    
public:
    Box(double w) : width(w) {}
    
    // Friend function declaration
    friend void printWidth(Box box);
};

// Friend function definition
void printWidth(Box box) {
    // Can access private members as it's a friend
    cout << "Width of box: " << box.width << endl;
}

// Static member example
class Counter {
private:
    static int count; // Static member variable
    
public:
    Counter() { count++; }
    ~Counter() { count--; }
    
    static int getCount() { return count; } // Static member function
};

// Initialize static member
int Counter::count = 0;

int main() {
    // Polymorphism example
    Shape *shapes[2];
    shapes[0] = new Rectangle(5, 3);
    shapes[1] = new Circle(2.5);
    
    cout << "Polymorphism Example:" << endl;
    for (int i = 0; i < 2; i++) {
        shapes[i]->display();
        cout << endl;
        delete shapes[i];
    }
    
    // Friend function example
    Box box(10.5);
    printWidth(box);
    
    // Static member example
    cout << "\nInitial count: " << Counter::getCount() << endl;
    Counter c1;
    cout << "After creating first object: " << Counter::getCount() << endl;
    {
        Counter c2;
        cout << "After creating second object: " << Counter::getCount() << endl;
    }
    cout << "After second object goes out of scope: " << Counter::getCount() << endl;
    
    return 0;
}

Shows polymorphism, abstract classes, friend functions, and static members in OOP.

11. Standard Template Library (STL)

STL Containers
stl_containers.cpp
#include <iostream>
#include <vector>
#include <list>
#include <map>
#include <set>
#include <stack>
#include <queue>
using namespace std;

int main() {
    // Vector - dynamic array
    cout << "Vector Example:" << endl;
    vector nums = {10, 20, 30, 40, 50};
    nums.push_back(60);
    nums.push_back(70);
    
    for (int num : nums) {
        cout << num << " ";
    }
    cout << endl << "Size: " << nums.size() << endl << endl;
    
    // List - doubly linked list
    cout << "List Example:" << endl;
    list names = {"Alice", "Bob", "Charlie"};
    names.push_front("Zoe");
    names.push_back("David");
    
    for (const auto &name : names) {
        cout << name << " ";
    }
    cout << endl << "Size: " << names.size() << endl << endl;
    
    // Map - key-value pairs
    cout << "Map Example:" << endl;
    map ageMap;
    ageMap["Alice"] = 25;
    ageMap["Bob"] = 30;
    ageMap["Charlie"] = 35;
    
    for (const auto &pair : ageMap) {
        cout << pair.first << ": " << pair.second << endl;
    }
    cout << "Size: " << ageMap.size() << endl << endl;
    
    // Set - unique elements
    cout << "Set Example:" << endl;
    set uniqueNums = {5, 2, 8, 2, 5, 9, 1};
    uniqueNums.insert(3);
    uniqueNums.insert(7);
    
    for (int num : uniqueNums) {
        cout << num << " ";
    }
    cout << endl << "Size: " << uniqueNums.size() << endl << endl;
    
    // Stack - LIFO
    cout << "Stack Example:" << endl;
    stack numStack;
    numStack.push(10);
    numStack.push(20);
    numStack.push(30);
    
    while (!numStack.empty()) {
        cout << numStack.top() << " ";
        numStack.pop();
    }
    cout << endl << endl;
    
    // Queue - FIFO
    cout << "Queue Example:" << endl;
    queue nameQueue;
    nameQueue.push("Alice");
    nameQueue.push("Bob");
    nameQueue.push("Charlie");
    
    while (!nameQueue.empty()) {
        cout << nameQueue.front() << " ";
        nameQueue.pop();
    }
    cout << endl;
    
    return 0;
}

Demonstrates various STL containers including vector, list, map, set, stack, and queue.

STL Algorithms
stl_algorithms.cpp
#include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>
#include <iterator>
using namespace std;

int main() {
    vector numbers = {5, 2, 8, 1, 9, 3, 7, 4, 6};
    
    cout << "Original vector: ";
    for (int num : numbers) {
        cout << num << " ";
    }
    cout << endl;
    
    // Sorting
    sort(numbers.begin(), numbers.end());
    cout << "Sorted: ";
    for (int num : numbers) {
        cout << num << " ";
    }
    cout << endl;
    
    // Reversing
    reverse(numbers.begin(), numbers.end());
    cout << "Reversed: ";
    for (int num : numbers) {
        cout << num << " ";
    }
    cout << endl;
    
    // Finding elements
    auto it = find(numbers.begin(), numbers.end(), 7);
    if (it != numbers.end()) {
        cout << "Found 7 at position: " << distance(numbers.begin(), it) << endl;
    } else {
        cout << "7 not found" << endl;
    }
    
    // Counting elements
    int countFives = count(numbers.begin(), numbers.end(), 5);
    cout << "Number of 5s: " << countFives << endl;
    
    // Accumulate (sum)
    int total = accumulate(numbers.begin(), numbers.end(), 0);
    cout << "Sum of all elements: " << total << endl;
    
    // Min and max elements
    auto minIt = min_element(numbers.begin(), numbers.end());
    auto maxIt = max_element(numbers.begin(), numbers.end());
    cout << "Min element: " << *minIt << endl;
    cout << "Max element: " << *maxIt << endl;
    
    // Binary search (requires sorted collection)
    sort(numbers.begin(), numbers.end());
    bool found = binary_search(numbers.begin(), numbers.end(), 3);
    cout << "3 found using binary search: " << boolalpha << found << endl;
    
    // Lambda expressions with algorithms
    cout << "Numbers greater than 5: ";
    for_each(numbers.begin(), numbers.end(), [](int n) {
        if (n > 5) cout << n << " ";
    });
    cout << endl;
    
    // Transform algorithm
    vector squaredNumbers(numbers.size());
    transform(numbers.begin(), numbers.end(), squaredNumbers.begin(), [](int n) {
        return n * n;
    });
    
    cout << "Squared numbers: ";
    for (int num : squaredNumbers) {
        cout << num << " ";
    }
    cout << endl;
    
    return 0;
}

Shows various STL algorithms for sorting, searching, transforming, and processing data.

12. File Handling

Basic File Operations
file_basics.cpp
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main() {
    string filename = "example.txt";
    
    // Writing to a file
    ofstream outFile(filename);
    if (outFile.is_open()) {
        outFile << "Hello, File Handling in C++!" << endl;
        outFile << "This is a second line." << endl;
        outFile << "And a third line." << endl;
        outFile.close();
        cout << "File written successfully." << endl;
    } else {
        cout << "Unable to open file for writing." << endl;
        return 1;
    }
    
    // Reading from a file
    ifstream inFile(filename);
    if (inFile.is_open()) {
        string line;
        cout << "\nFile content:" << endl;
        while (getline(inFile, line)) {
            cout << line << endl;
        }
        inFile.close();
    } else {
        cout << "Unable to open file for reading." << endl;
        return 1;
    }
    
    // Appending to a file
    ofstream appFile(filename, ios::app);
    if (appFile.is_open()) {
        appFile << "This line was appended." << endl;
        appFile.close();
        cout << "Content appended to file." << endl;
    } else {
        cout << "Unable to open file for appending." << endl;
        return 1;
    }
    
    // Reading appended content
    cout << "\nFile content after appending:" << endl;
    inFile.open(filename);
    if (inFile.is_open()) {
        string line;
        while (getline(inFile, line)) {
            cout << line << endl;
        }
        inFile.close();
    }
    
    // Checking file state
    ifstream testFile("nonexistent.txt");
    if (testFile.fail()) {
        cout << "\nFailed to open nonexistent file (as expected)." << endl;
    }
    
    // Getting file size
    inFile.open(filename, ios::binary | ios::ate);
    if (inFile.is_open()) {
        streamsize size = inFile.tellg();
        cout << "\nFile size: " << size << " bytes" << endl;
        inFile.close();
    }
    
    return 0;
}

Demonstrates basic file operations including reading, writing, and appending to files.

Binary File Operations
binary_files.cpp
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;

// Structure for binary data
struct Employee {
    int id;
    char name[50];
    double salary;
};

int main() {
    vector employees = {
        {101, "John Doe", 50000.0},
        {102, "Jane Smith", 60000.0},
        {103, "Bob Johnson", 55000.0}
    };
    
    string filename = "employees.dat";
    
    // Writing binary data
    ofstream outFile(filename, ios::binary);
    if (outFile.is_open()) {
        for (const auto &emp : employees) {
            outFile.write(reinterpret_cast(&emp), sizeof(Employee));
        }
        outFile.close();
        cout << "Binary data written successfully." << endl;
    } else {
        cout << "Unable to open file for binary writing." << endl;
        return 1;
    }
    
    // Reading binary data
    vector readEmployees;
    ifstream inFile(filename, ios::binary);
    if (inFile.is_open()) {
        Employee emp;
        while (inFile.read(reinterpret_cast(&emp), sizeof(Employee))) {
            readEmployees.push_back(emp);
        }
        inFile.close();
        
        cout << "\nEmployees read from binary file:" << endl;
        for (const auto &e : readEmployees) {
            cout << "ID: " << e.id 
                 << ", Name: " << e.name 
                 << ", Salary: " << e.salary << endl;
        }
    } else {
        cout << "Unable to open file for binary reading." << endl;
        return 1;
    }
    
    // Random access in binary files
    fstream file(filename, ios::binary | ios::in | ios::out);
    if (file.is_open()) {
        // Read second employee
        Employee emp;
        file.seekg(sizeof(Employee) * 1); // Seek to second record
        file.read(reinterpret_cast(&emp), sizeof(Employee));
        cout << "\nSecond employee: " << emp.name << endl;
        
        // Update salary of second employee
        emp.salary = 65000.0;
        file.seekp(sizeof(Employee) * 1); // Seek to position for writing
        file.write(reinterpret_cast(&emp), sizeof(Employee));
        
        // Read back to verify
        file.seekg(sizeof(Employee) * 1);
        file.read(reinterpret_cast(&emp), sizeof(Employee));
        cout << "Updated salary: " << emp.salary << endl;
        
        file.close();
    }
    
    // Working with file positions
    inFile.open(filename, ios::binary);
    if (inFile.is_open()) {
        inFile.seekg(0, ios::end);
        streampos fileSize = inFile.tellg();
        int numRecords = fileSize / sizeof(Employee);
        cout << "\nNumber of records in file: " << numRecords << endl;
        inFile.close();
    }
    
    return 0;
}

Shows binary file operations including reading, writing, and random access in files.

13. Exception Handling

Basic Exception Handling
exceptions.cpp
#include <iostream>
#include <stdexcept>
#include <string>
using namespace std;

// Function that throws an exception
double divide(double numerator, double denominator) {
    if (denominator == 0) {
        throw runtime_error("Division by zero error!");
    }
    return numerator / denominator;
}

// Custom exception class
class MyException : public exception {
private:
    string message;
    
public:
    MyException(const string& msg) : message(msg) {}
    
    const char* what() const noexcept override {
        return message.c_str();
    }
};

int main() {
    // Basic try-catch block
    try {
        double result = divide(10.0, 0.0);
        cout << "Result: " << result << endl;
    } catch (const runtime_error& e) {
        cout << "Caught runtime error: " << e.what() << endl;
    }
    
    // Multiple catch blocks
    try {
        int arr[5] = {1, 2, 3, 4, 5};
        cout << "Array element at index 10: " << arr[10] << endl; // Out of bounds
    } catch (const out_of_range& e) {
        cout << "Out of range error: " << e.what() << endl;
    } catch (const exception& e) {
        cout << "Standard exception: " << e.what() << endl;
    } catch (...) {
        cout << "Unknown exception caught" << endl;
    }
    
    // Custom exception
    try {
        throw MyException("This is a custom exception!");
    } catch (const MyException& e) {
        cout << "Caught custom exception: " << e.what() << endl;
    }
    
    // Nested try-catch blocks
    try {
        try {
            throw invalid_argument("Invalid argument exception");
        } catch (const invalid_argument& e) {
            cout << "Inner catch: " << e.what() << endl;
            throw; // Rethrow the exception
        }
    } catch (const invalid_argument& e) {
        cout << "Outer catch: " << e.what() << endl;
    }
    
    // Exception safety - RAII (Resource Acquisition Is Initialization)
    class FileHandler {
    private:
        string filename;
        ofstream file;
        
    public:
        FileHandler(const string& name) : filename(name) {
            file.open(filename);
            if (!file.is_open()) {
                throw runtime_error("Failed to open file: " + filename);
            }
            cout << "File opened successfully: " << filename << endl;
        }
        
        ~FileHandler() {
            if (file.is_open()) {
                file.close();
                cout << "File closed: " << filename << endl;
            }
        }
        
        void write(const string& content) {
            if (!file.is_open()) {
                throw runtime_error("File is not open");
            }
            file << content << endl;
        }
    };
    
    try {
        FileHandler fh("test.txt");
        fh.write("Hello, RAII!");
        // File will be automatically closed when fh goes out of scope
    } catch (const exception& e) {
        cout << "File error: " << e.what() << endl;
    }
    
    return 0;
}

Demonstrates basic exception handling with try-catch blocks and custom exceptions.

Advanced Exception Handling
advanced_exceptions.cpp
#include <iostream>
#include <stdexcept>
#include <vector>
#include <memory>
using namespace std;

// Exception specification (noexcept)
void safeFunction() noexcept {
    cout << "This function doesn't throw exceptions" << endl;
}

// Function with exception specification
void mightThrow() throw(runtime_error, logic_error) {
    // This function can only throw runtime_error or logic_error
    throw runtime_error("Expected exception");
}

// Custom exception hierarchy
class BaseException : public exception {
protected:
    string message;
    
public:
    BaseException(const string& msg) : message(msg) {}
    virtual const char* what() const noexcept override {
        return message.c_str();
    }
};

class MathException : public BaseException {
public:
    MathException(const string& msg) : BaseException(msg) {}
};

class DivisionException : public MathException {
public:
    DivisionException(const string& msg) : MathException(msg) {}
};

// Function that uses custom exceptions
double safeDivide(double a, double b) {
    if (b == 0) {
        throw DivisionException("Division by zero in safeDivide");
    }
    return a / b;
}

// Class with exception-safe methods
class ExceptionSafeVector {
private:
    vector data;
    
public:
    void addNumber(int num) {
        data.push_back(num);
    }
    
    int getNumberAt(size_t index) const {
        if (index >= data.size()) {
            throw out_of_range("Index out of range");
        }
        return data[index];
    }
    
    // Exception-safe swap
    void swap(ExceptionSafeVector& other) noexcept {
        data.swap(other.data);
    }
    
    // Strong exception guarantee method
    void insertWithStrongGuarantee(size_t index, int value) {
        vector newData = data; // Copy
        if (index > newData.size()) {
            throw out_of_range("Index out of range");
        }
        newData.insert(newData.begin() + index, value);
        data.swap(newData); // Commit (no-throw)
    }
};

int main() {
    // noexcept demonstration
    cout << "safeFunction is noexcept: " << noexcept(safeFunction()) << endl;
    
    // Exception specifications
    try {
        mightThrow();
    } catch (const exception& e) {
        cout << "Caught: " << e.what() << endl;
    }
    
    // Custom exception hierarchy
    try {
        throw DivisionException("Custom division error");
    } catch (const DivisionException& e) {
        cout << "DivisionException: " << e.what() << endl;
    } catch (const MathException& e) {
        cout << "MathException: " << e.what() << endl;
    } catch (const BaseException& e) {
        cout << "BaseException: " << e.what() << endl;
    }
    
    // Exception-safe class usage
    ExceptionSafeVector esv;
    esv.addNumber(10);
    esv.addNumber(20);
    esv.addNumber(30);
    
    try {
        cout << "Element at index 1: " << esv.getNumberAt(1) << endl;
        cout << "Element at index 5: " << esv.getNumberAt(5) << endl;
    } catch (const out_of_range& e) {
        cout << "Error: " << e.what() << endl;
    }
    
    // Strong exception guarantee
    try {
        esv.insertWithStrongGuarantee(10, 100); // This should fail
    } catch (const exception& e) {
        cout << "Insert failed: " << e.what() << endl;
        // Original state is preserved due to strong guarantee
    }
    
    // Using standard exception-safe utilities
    unique_ptr ptr(new int(42));
    // Even if exception occurs, memory will be freed
    
    try {
        throw logic_error("Some logic error");
    } catch (...) {
        cout << "Caught exception using catch-all" << endl;
    }
    
    // Rethrowing exceptions
    try {
        try {
            throw runtime_error("Original error");
        } catch (const runtime_error& e) {
            cout << "Caught: " << e.what() << endl;
            throw; // Rethrow
        }
    } catch (const runtime_error& e) {
        cout << "Rethrown caught: " << e.what() << endl;
    }
    
    return 0;
}

Shows advanced exception handling techniques including custom exceptions, exception specifications, and exception safety guarantees.

14. Modern C++ (C++11/14/17/20)

C++11/14 Features
modern_cpp.cpp
#include <iostream>
#include <vector>
#include <memory>
#include <typeinfo>
#include <functional>
using namespace std;

// Auto and decltype
auto add(auto a, auto b) -> decltype(a + b) {
    return a + b;
}

// Lambda expressions
void lambdaDemo() {
    vector numbers = {1, 2, 3, 4, 5};
    
    // Basic lambda
    auto print = [](int n) { cout << n << " "; };
    for_each(numbers.begin(), numbers.end(), print);
    cout << endl;
    
    // Lambda with capture
    int threshold = 3;
    cout << "Numbers greater than " << threshold << ": ";
    for_each(numbers.begin(), numbers.end(), [threshold](int n) {
        if (n > threshold) cout << n << " ";
    });
    cout << endl;
    
    // Mutable lambda
    int counter = 0;
    auto incrementer = [counter]() mutable {
        cout << "Counter: " << ++counter << endl;
    };
    incrementer();
    incrementer();
}

// Range-based for loop
void rangeBasedFor() {
    vector words = {"Modern", "C++", "Features"};
    
    cout << "Words: ";
    for (const auto& word : words) {
        cout << word << " ";
    }
    cout << endl;
}

// Initializer lists
void initializerListDemo() {
    // Uniform initialization
    vector nums{1, 2, 3, 4, 5};
    int arr[]{10, 20, 30};
    
    cout << "Vector: ";
    for (auto n : nums) cout << n << " ";
    cout << endl;
}

// Smart pointers
void smartPointerDemo() {
    // Unique pointer
    unique_ptr uptr(new int(42));
    cout << "Unique ptr: " << *uptr << endl;
    
    // Shared pointer
    shared_ptr sptr1 = make_shared(100);
    {
        shared_ptr sptr2 = sptr1;
        cout << "Shared ptr use count: " << sptr1.use_count() << endl;
    }
    cout << "Shared ptr use count: " << sptr1.use_count() << endl;
    
    // Weak pointer
    weak_ptr wptr = sptr1;
    if (auto locked = wptr.lock()) {
        cout << "Weak ptr locked value: " << *locked << endl;
    }
}

// constexpr
constexpr int square(int x) {
    return x * x;
}

// nullptr
void process(int* ptr) {
    if (ptr != nullptr) {
        cout << "Processing: " << *ptr << endl;
    } else {
        cout << "Null pointer" << endl;
    }
}

int main() {
    cout << "=== Modern C++ Features ===" << endl;
    
    // Auto and decltype
    auto result = add(5, 3.5);
    cout << "add(5, 3.5) = " << result << endl;
    cout << "Type: " << typeid(result).name() << endl;
    
    // Lambda expressions
    lambdaDemo();
    
    // Range-based for
    rangeBasedFor();
    
    // Initializer lists
    initializerListDemo();
    
    // Smart pointers
    smartPointerDemo();
    
    // constexpr
    constexpr int squared = square(5);
    cout << "constexpr square(5) = " << squared << endl;
    
    // nullptr
    int value = 42;
    process(&value);
    process(nullptr);
    
    // Type inference
    auto str = "Hello Modern C++";
    cout << "Auto variable: " << str << endl;
    
    // Static assert
    static_assert(sizeof(void*) == 8, "Not 64-bit architecture");
    
    return 0;
}

Demonstrates modern C++ features including auto, lambdas, smart pointers, and other C++11/14 features.

C++17/20 Features
cpp17_20.cpp
#include <iostream>
#include <variant>
#include <optional>
#include <tuple>
#include <string>
#include <vector>
#include <algorithm>
#include <ranges>
using namespace std;

// Structured bindings (C++17)
tuple getPerson() {
    return {101, "Alice", 25.5};
}

void structuredBindings() {
    auto [id, name, age] = getPerson();
    cout << "ID: " << id << ", Name: " << name << ", Age: " << age << endl;
}

// std::variant (C++17)
void variantDemo() {
    variant v;
    v = 42;
    cout << "Variant holds int: " << get(v) << endl;
    
    v = "Hello";
    cout << "Variant holds string: " << get(v) << endl;
    
    // Visit pattern
    visit([](auto&& arg) {
        using T = decay_t;
        if constexpr (is_same_v) {
            cout << "int: " << arg << endl;
        } else if constexpr (is_same_v) {
            cout << "string: " << arg << endl;
        } else if constexpr (is_same_v) {
            cout << "double: " << arg << endl;
        }
    }, v);
}

// std::optional (C++17)
optional findNumber(const vector& nums, int target) {
    auto it = find(nums.begin(), nums.end(), target);
    if (it != nums.end()) {
        return *it;
    }
    return nullopt;
}

void optionalDemo() {
    vector numbers = {1, 3, 5, 7, 9};
    
    if (auto result = findNumber(numbers, 5)) {
        cout << "Found: " << *result << endl;
    } else {
        cout << "Not found" << endl;
    }
    
    if (auto result = findNumber(numbers, 6)) {
        cout << "Found: " << *result << endl;
    } else {
        cout << "Not found" << endl;
    }
}

// if constexpr (C++17)
template
void processValue(const T& value) {
    if constexpr (is_integral_v) {
        cout << "Integral: " << value * 2 << endl;
    } else if constexpr (is_floating_point_v) {
        cout << "Floating: " << value + 0.5 << endl;
    } else {
        cout << "Other: " << value << endl;
    }
}

// Concepts (C++20)
template
concept Numeric = is_arithmetic_v;

template
T square(T x) {
    return x * x;
}

// Ranges (C++20)
void rangesDemo() {
    vector numbers = {5, 2, 8, 1, 9, 3, 7, 4, 6};
    
    cout << "Original: ";
    for (auto n : numbers) cout << n << " ";
    cout << endl;
    
    // Filter and transform using ranges
    auto result = numbers 
        | views::filter([](int n) { return n % 2 == 0; })
        | views::transform([](int n) { return n * 2; });
    
    cout << "Even numbers doubled: ";
    for (auto n : result) cout << n << " ";
    cout << endl;
}

// Spaceship operator (C++20)
#include <compare>
struct Point {
    int x, y;
    
    auto operator<=>(const Point&) const = default;
};

// Modules (C++20) - Note: This is a preview, not fully supported everywhere
// import ;  // Not yet widely supported

int main() {
    cout << "=== C++17/20 Features ===" << endl;
    
    // Structured bindings
    structuredBindings();
    
    // Variant
    variantDemo();
    
    // Optional
    optionalDemo();
    
    // if constexpr
    processValue(10);
    processValue(3.14);
    processValue("Hello");
    
    // Concepts
    cout << "square(5) = " << square(5) << endl;
    cout << "square(2.5) = " << square(2.5) << endl;
    
    // Ranges
    rangesDemo();
    
    // Spaceship operator
    Point p1{1, 2}, p2{1, 2}, p3{3, 4};
    cout << "p1 == p2: " << (p1 == p2) << endl;
    cout << "p1 < p3: " << (p1 < p3) << endl;
    
    // Initializers in if/switch (C++17)
    if (auto it = find(vector{1, 2, 3, 4}, 3); it != vector{1, 2, 3, 4}.end()) {
        cout << "Found: " << *it << endl;
    }
    
    // inline variables (C++17)
    struct InlineDemo {
        static inline int count = 0; // No need for out-of-line definition
    };
    cout << "Inline variable: " << InlineDemo::count << endl;
    
    return 0;
}

Shows modern C++ features from C++17 and C++20 including structured bindings, variant, optional, concepts, and ranges.

More C++ Resources

Learning Resources

Other Languages

About NikhilLearnHub

Enhance your skills with us

© 2025 NikhilLearnHub. All rights reserved.