Basic Syntax and Structure

Hello World Program

#include <iostream>

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

Comments

// This is a single-line comment

/* This is a
   multi-line comment
   that spans several lines */

int x = 5; // Inline comment

Variables and Data Types

// Integer types
int age = 25;           // 4 bytes
short height = 175;     // 2 bytes
long population = 7800000000L;

// Floating-point types
float price = 19.99f;   // 4 bytes
double pi = 3.14159265359; // 8 bytes

// Character and String
char grade = 'A';       // 1 byte
std::string name = "John Doe";

// Boolean type
bool isActive = true;   // 1 byte

Operators

// Arithmetic operators
int a = 10, b = 3;
int sum = a + b;        // Addition
int diff = a - b;       // Subtraction
int product = a * b;    // Multiplication
int quotient = a / b;   // Division
int remainder = a % b;  // Modulus

// Assignment operators
int x = 5;
x += 3;                 // x = x + 3
x -= 2;                 // x = x - 2
x *= 4;                 // x = x * 4
x /= 2;                 // x = x / 2

// Comparison operators
bool isEqual = (a == b);
bool isGreater = (a > b);
bool isLess = (a < b);
bool isNotEqual = (a != b);

Control Structures

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

// Switch statement
switch (day) {
    case 1: dayName = "Monday"; break;
    case 2: dayName = "Tuesday"; break;
    case 3: dayName = "Wednesday"; break;
    default: dayName = "Unknown"; break;
}

Loops

// For loop
for (int i = 0; i < 10; i++) {
    std::cout << i << " ";
}

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

// Do-while loop
int num = 1;
do {
    std::cout << num << " ";
    num++;
} while (num <= 5);

Functions

// Function declaration
int add(int a, int b);

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

// Function with default parameters
void printMessage(std::string msg = "Hello") {
    std::cout << msg << std::endl;
}

// Function call
int result = add(5, 3);
printMessage("Custom message");

Arrays and Vectors

// Static array
int numbers[5] = {1, 2, 3, 4, 5};

// Array access
int first = numbers[0];
int last = numbers[4];

// Vector (dynamic array)
#include <vector>
std::vector<int> vec = {10, 20, 30};
vec.push_back(40);      // Add element
vec.pop_back();         // Remove last element

// 2D array
int matrix[3][3] = {
    {1, 2, 3},
    {4, 5, 6},
    {7, 8, 9}
};

Pointers and References

// Pointer declaration
int* ptr;               // Pointer to int
int value = 42;
ptr = &value;           // Address of value

// Dereferencing
int deref = *ptr;       // Get value at address

// Reference
int& ref = value;       // Reference to value
ref = 100;              // Changes value directly

// Dynamic memory
int* dynamicPtr = new int(25);
delete dynamicPtr;       // Free memory

// Smart pointers (C++11+)
#include <memory>
std::unique_ptr<int> smartPtr = std::make_unique<int>(42);

Classes and Objects

// Class definition
class Rectangle {
private:
    double width, height;
    
public:
    // Constructor
    Rectangle(double w, double h) : width(w), height(h) {}
    
    // Member functions
    double getArea() {
        return width * height;
    }
    
    void setDimensions(double w, double h) {
        width = w;
        height = h;
    }
};

// Object creation
Rectangle rect(5.0, 3.0);
double area = rect.getArea();

Namespaces and Scope

// Namespace declaration
namespace Math {
    const double PI = 3.14159;
    
    double square(double x) {
        return x * x;
    }
}

// Using namespace
using namespace Math;
double result = square(5.0);

// Scope resolution operator
double pi = Math::PI;

// Global scope
::globalVariable = 100;

Exception Handling

// Try-catch block
try {
    int result = divide(a, b);
    std::cout << "Result: " << result << std::endl;
} catch (const std::exception& e) {
    std::cout << "Error: " << e.what() << std::endl;
}

// Throwing exceptions
int divide(int a, int b) {
    if (b == 0) {
        throw std::runtime_error("Division by zero");
    }
    return a / b;
}

File I/O

#include <fstream>

// Writing to file
std::ofstream outFile("output.txt");
outFile << "Hello, File!" << std::endl;
outFile.close();

// Reading from file
std::ifstream inFile("input.txt");
std::string line;
while (std::getline(inFile, line)) {
    std::cout << line << std::endl;
}
inFile.close();