Algo Infinity Verse

Start Your Journey With C++ Programming Beginner-Friendly Concepts, Code & Practice

|
0 Topics
0 Examples
0 Exercises

Learn C++

Master the fundamentals of C++ with clear explanations and hands-on examples

0 / 10 topics completed
01

Introduction to C++

C++ is a powerful, high-performance programming language created by Bjarne Stroustrup in 1985 at Bell Labs. It extends the C language with object-oriented features, making it one of the most versatile languages ever created. C++ gives you fine-grained control over system resources and memory.

Why Learn C++?

  • High Performance – Used in game engines, operating systems, and browsers
  • Object-Oriented – Supports classes, inheritance, and polymorphism
  • Manual Memory Control – Pointers and direct memory management
  • Industry Standard – Used by Google, Microsoft, Adobe, and game studios
  • Foundation for DSA – The go-to language for competitive programming

Your first C++ program is the classic "Hello, World!":

C++
#include <iostream>
using namespace std;

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

Every C++ program needs a main() function — it's the entry point. The #include <iostream> directive lets you use input/output features. return 0; signals successful execution.

02

Installation & Setup

To write and run C++ code, you need a C++ compiler and a text editor or IDE. The most common compilers are g++ (GNU Compiler Collection) and clang++.

Installing a Compiler

  • Linux – Install via package manager: sudo apt install g++
  • macOS – Install Xcode Command Line Tools: xcode-select --install
  • Windows – Download MinGW-w64 or use Visual Studio with the "Desktop development with C++" workload
Bash
# Verify your compiler installation
g++ --version
clang++ --version

Choosing an IDE

  • VS Code – Lightweight with C++ extension pack (recommended)
  • CLion – Full-featured C++ IDE by JetBrains
  • Code::Blocks – Free, beginner-friendly IDE
Bash
# Compile and run a C++ program
g++ hello.cpp -o hello    # compiles to executable
./hello                   # runs the executable

C++ is a compiled language: you write .cpp source files, compile them to a machine-executable binary with g++, and run the binary directly on your operating system.

03

Variables & Data Types

In C++, every variable must have a declared type. C++ is statically typed — once you declare a variable's type, it cannot hold a different type of value.

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

int main() {
    string name = "Alice";    // Text
    int age = 25;               // Whole number
    double height = 5.7;        // Decimal number
    bool isStudent = true;      // true / false
    char grade = 'A';           // Single character

    cout << name << endl;
    cout << age << endl;
    cout << height << endl;
    cout << isStudent << endl;
    cout << grade << endl;
    return 0;
}
Output
Alice
25
5.7
1
A
Type Size Example Description
int4 bytes42Whole number
double8 bytes3.14Double precision decimal
float4 bytes3.14fSingle precision decimal
char1 byte'A'Single ASCII character
bool1 bytetrue/falseLogical value
stringVariable"Hello"Sequence of characters (from <string>)
💡

C++ also supports unsigned types (only non-negative values), long and short variants, and the auto keyword for type inference: auto x = 42; automatically deduces int.

Practice: Variables & Data Types

Create variables of different types and print them:

  1. Create an int variable score with value 95
  2. Create a double variable gpa with value 3.85
  3. Create a string variable city with value "New York"
  4. Create a bool variable passed set to true
  5. Print each variable using cout
C++
int score = 95;
double gpa = 3.85;
string city = "New York";
bool passed = true;

cout << "Score: " << score << endl;
cout << "GPA: " << gpa << endl;
cout << "City: " << city << endl;
cout << "Passed: " << passed << endl;
04

Input & Output

C++ uses cout (console output) and cin (console input) from the standard library. They are defined in the <iostream> header.

cout — Displaying Output

cout << "text" << endl; prints text followed by a newline. Use << to chain multiple values together.

C++
#include <iostream>
using namespace std;

int main() {
    string name = "Alice";
    int age = 25;

    cout << "My name is " << name << " and I am " << age << " years old." << endl;
    return 0;
}
Output
My name is Alice and I am 25 years old.

cin — Reading User Input

cin >> variable reads input from the console. The extraction operator (>>) reads formatted data.

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

int main() {
    string name;
    int age;

    cout << "What is your name? ";
    getline(cin, name);

    cout << "How old are you? ";
    cin >> age;

    cout << "Hello, " << name << "! In 10 years you will be " << (age + 10) << "." << endl;
    return 0;
}
⚠️

cin >> stops at whitespace, so it won't read a full name like "John Doe". Use getline(cin, name) to read an entire line. However, after cin >>, there's often a leftover newline — use cin.ignore() before getline to clear it.

Practice: Input & Output

Write a program that asks the user for their name and favorite color, then prints a greeting.

  1. Include <iostream> and <string>
  2. Ask for name and favorite color using getline(cin, variable)
  3. Print: "Hello {name}, your favorite color is {color}!"
C++
#include <iostream>
#include <string>
using namespace std;

int main() {
    string name, color;

    cout << "Enter your name: ";
    getline(cin, name);

    cout << "Enter your favorite color: ";
    getline(cin, color);

    cout << "Hello " << name << ", your favorite color is " << color << "!" << endl;
    return 0;
}
05

Operators

Operators perform operations on variables and values. C++ supports arithmetic, assignment, comparison, logical, and bitwise operators.

Category Operators Example
Arithmetic+ - * / %10 + 5 → 15
Assignment= += -= *= /= %=x += 5
Comparison== != < > <= >=10 > 5 → true
Logical&& || !true && false → false
Increment/Decrement++ --i++
C++
#include <iostream>
using namespace std;

int main() {
    int a = 10, b = 5;

    // Arithmetic
    int sum = a + b;
    int product = a * b;
    int remainder = a % b;

    // Comparison & Logical
    bool isGreater = a > b;
    bool bothPositive = (a > 0) && (b > 0);

    cout << "Sum: " << sum << endl;
    cout << "Product: " << product << endl;
    cout << "Remainder: " << remainder << endl;
    cout << "Is a > b? " << isGreater << endl;
    cout << "Both positive? " << bothPositive << endl;
    return 0;
}
Output
Sum: 15
Product: 50
Remainder: 0
Is a > b? true
Both positive? true
Practice: Operators

Calculate the area and perimeter of a rectangle with width 8 and length 12.

  1. Create int variables width and length
  2. Calculate area = width * length
  3. Calculate perimeter = 2 * (width + length)
  4. Print both results using cout
C++
#include <iostream>
using namespace std;

int main() {
    int width = 8;
    int length = 12;
    int area = width * length;
    int perimeter = 2 * (width + length);

    cout << "Area: " << area << endl;
    cout << "Perimeter: " << perimeter << endl;
    return 0;
}
06

Conditional Statements

Conditionals let your program make decisions. C++ supports if, else if, else, and switch statements.

C++
#include <iostream>
using namespace std;

int main() {
    int score = 85;
    char grade;

    if (score >= 90) {
        grade = 'A';
    } else if (score >= 80) {
        grade = 'B';
    } else if (score >= 70) {
        grade = 'C';
    } else {
        grade = 'F';
    }

    cout << "Score: " << score << " → Grade: " << grade << endl;
    return 0;
}
Output
Score: 85 → Grade: B

switch Statement

The switch statement is useful when checking a variable against many specific values.

C++
#include <iostream>
using namespace std;

int main() {
    int day = 3;
    string dayName;

    switch (day) {
        case 1:  dayName = "Monday";    break;
        case 2:  dayName = "Tuesday";   break;
        case 3:  dayName = "Wednesday"; break;
        case 4:  dayName = "Thursday";  break;
        case 5:  dayName = "Friday";    break;
        default: dayName = "Weekend";
    }

    cout << dayName << endl;
    return 0;
}
Output
Wednesday
Practice: Conditionals

Write a program that reads a number and prints whether it is positive, negative, or zero.

  1. Use cin to read an integer
  2. Use if/else if/else to check the number
  3. Print the result using cout
C++
#include <iostream>
using namespace std;

int main() {
    int num;
    cout << "Enter a number: ";
    cin >> num;

    if (num > 0) {
        cout << "Positive" << endl;
    } else if (num < 0) {
        cout << "Negative" << endl;
    } else {
        cout << "Zero" << endl;
    }
    return 0;
}
07

Loops (for, while, do-while)

Loops let you repeat a block of code. C++ has three loop types: for, while, and do-while.

for Loop

Use for when you know how many times to iterate.

C++
#include <iostream>
using namespace std;

int main() {
    // Count from 0 to 4
    for (int i = 0; i < 5; i++) {
        cout << "Count: " << i << endl;
    }

    // Range-based for loop (C++11)
    string fruits[] = {"apple", "banana", "cherry"};
    for (string fruit : fruits) {
        cout << fruit << endl;
    }
    return 0;
}
Output
Count: 0
Count: 1
Count: 2
Count: 3
Count: 4
apple
banana
cherry

while & do-while Loops

while checks the condition first; do-while runs the body at least once.

C++
#include <iostream>
using namespace std;

int main() {
    // while loop
    int count = 0;
    while (count < 5) {
        cout << "While: " << count << endl;
        count++;
    }

    // do-while loop
    int num = 0;
    do {
        cout << "Do-while: " << num << endl;
        num++;
    } while (num < 5);
    return 0;
}
⚠️

Always ensure your loop condition eventually becomes false to avoid infinite loops. Use break to exit early and continue to skip the current iteration.

Practice: Loops

Write two programs:

  1. Use a for loop to print all even numbers from 2 to 20
  2. Use a while loop to calculate the sum of numbers from 1 to 100
C++
#include <iostream>
using namespace std;

int main() {
    // Even numbers 2-20
    for (int i = 2; i <= 20; i += 2) {
        cout << i << endl;
    }

    // Sum of 1 to 100
    int sum = 0;
    int n = 1;
    while (n <= 100) {
        sum += n;
        n++;
    }
    cout << "Sum: " << sum << endl;
    return 0;
}
08

Functions

Functions (also called methods) are reusable blocks of code. They help you avoid repetition and organize your program into logical pieces.

C++
#include <iostream>
using namespace std;

// Function with parameters and return value
int add(int a, int b) {
    return a + b;
}

// Void function (no return value)
void greet(string name) {
    cout << "Hello, " << name << "!" << endl;
}

int main() {
    int sum = add(10, 5);
    cout << "Sum: " << sum << endl;

    greet("Alice");
    return 0;
}
Output
Sum: 15
Hello, Alice!

Function Overloading

C++ allows multiple functions with the same name as long as their parameters differ (number, type, or order).

C++
#include <iostream>
using namespace std;

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

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

int main() {
    cout << multiply(5, 3) << endl;      // 15
    cout << multiply(2.5, 4.0) << endl;  // 10
    return 0;
}
Practice: Functions
  1. Write a function isEven(int n) that returns true if n is even
  2. Write a function factorial(int n) that returns the factorial of n
  3. Call both from main() and print the results
C++
#include <iostream>
using namespace std;

bool isEven(int n) {
    return n % 2 == 0;
}

int factorial(int n) {
    if (n <= 1) return 1;
    return n * factorial(n - 1);
}

int main() {
    cout << isEven(4) << endl;           // 1 (true)
    cout << factorial(5) << endl;        // 120
    return 0;
}
09

Arrays & Strings

Arrays store multiple values of the same type. C++ strings (std::string) represent text and come with many built-in methods.

Arrays — Fixed-Size Collections

Arrays in C++ have a fixed length. You can use C-style arrays or std::array (C++11). Indexing starts at 0.

C++
#include <iostream>
using namespace std;

int main() {
    // C-style array
    int numbers[5] = {10, 20, 30, 40, 50};
    string fruits[] = {"apple", "banana", "cherry"};

    // Access and modify
    numbers[0] = 99;
    cout << numbers[0] << endl;      // 99
    cout << fruits[1] << endl;       // banana
    cout << "Size: " << sizeof(numbers) / sizeof(numbers[0]) << endl;
    return 0;
}

String Methods

The std::string class provides many useful methods for text manipulation.

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

int main() {
    string text = "Hello, C++!";

    cout << text.length() << endl;              // 11
    cout << text[0] << endl;                     // H
    cout << text.substr(7) << endl;              // C++!
    cout << text.find("C++") << endl;            // 7
    cout << text.replace(7, 3, "World") << endl; // Hello, World!
    return 0;
}
Practice: Arrays & Strings
  1. Create an array of 5 integers and calculate their sum using a for loop
  2. Write code to count how many vowels are in a given string
C++
#include <iostream>
#include <string>
using namespace std;

int main() {
    // Sum of array
    int nums[] = {10, 20, 30, 40, 50};
    int sum = 0;
    for (int n : nums) {
        sum += n;
    }
    cout << "Sum: " << sum << endl;

    // Count vowels
    string str = "hello world";
    int vowels = 0;
    for (char c : str) {
        c = tolower(c);
        if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') {
            vowels++;
        }
    }
    cout << "Vowels: " << vowels << endl;
    return 0;
}
10

Basic Object-Oriented Programming

C++ supports Object-Oriented Programming (OOP) with classes and objects. The core principles are Encapsulation, Inheritance, and Polymorphism.

Classes & Objects

A class is a blueprint. An object is an instance with its own state and behavior.

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

// Define a class
class Student {
public:
    string name;
    int age;

    // Constructor
    Student(string n, int a) {
        name = n;
        age = a;
    }

    void introduce() {
        cout << "Hi, I'm " << name << " and I'm " << age << " years old." << endl;
    }
};

int main() {
    // Create objects
    Student alice("Alice", 20);
    Student bob("Bob", 22);

    alice.introduce();
    bob.introduce();
    return 0;
}
Output
Hi, I'm Alice and I'm 20 years old.
Hi, I'm Bob and I'm 22 years old.
💡

Constructors have the same name as the class and no return type. The public: access specifier makes members accessible from outside the class. You can also use private: and protected: for data hiding.

Encapsulation

Bundle data and methods together, restricting direct access to fields using private with public getters/setters.

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

class Person {
private:
    string name;
    int age;

public:
    Person(string n, int a) : name(n), age(a) {}

    string getName() { return name; }
    int getAge() { return age; }

    void setAge(int a) {
        if (a > 0) age = a;
    }
};

int main() {
    Person p("Alice", 25);
    cout << p.getName() << " is " << p.getAge() << endl;
    return 0;
}

Inheritance & Polymorphism

Create a derived class from a base class using :. Polymorphism lets derived classes override base class behavior.

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

// Base class
class Animal {
public:
    string name;
    Animal(string n) : name(n) {}
    virtual void speak() {
        cout << name << " makes a sound" << endl;
    }
};

// Derived class
class Dog : public Animal {
public:
    Dog(string n) : Animal(n) {}

    void speak() override {
        cout << name << " barks!" << endl;
    }
};

int main() {
    Animal* a = new Dog("Buddy");
    a->speak();  // Buddy barks! (polymorphism)
    delete a;
    return 0;
}
Output
Buddy barks!

The Four Pillars of OOP in C++

  • Encapsulation – Bundle data & methods; use private with getters/setters
  • Inheritance – Derive classes with class Dog : public Animal
  • Polymorphismvirtual functions enable runtime method dispatch
  • Abstraction – Hide complexity using virtual functions and interfaces
Practice: OOP Concepts

Create a Vehicle base class and a Car derived class:

  1. Vehicle has a brand field and a virtual method honk()
  2. Car inherits from Vehicle with an additional model field
  3. Override honk() in Car to print a car-specific sound
  4. Create a Car object and call its methods
C++
#include <iostream>
#include <string>
using namespace std;

class Vehicle {
public:
    string brand;
    Vehicle(string b) : brand(b) {}
    virtual void honk() {
        cout << brand << " goes beep beep!" << endl;
    }
};

class Car : public Vehicle {
public:
    string model;
    Car(string b, string m) : Vehicle(b), model(m) {}

    void honk() override {
        cout << brand << " " << model << " goes HONK HONK!" << endl;
    }
};

int main() {
    Car myCar("Toyota", "Camry");
    myCar.honk();
    return 0;
}