1. Object Oriented Technology

  • Object Oriented Programming (OOP) is a programming paradigm that organizes software design around objects rather than functions and logic.

Core Concepts of OOP

ConceptDescription
ClassBlueprint/template for creating objects
ObjectInstance of a class
EncapsulationWrapping data and methods together
InheritanceDeriving new classes from existing ones
PolymorphismOne interface, many forms
AbstractionHiding complex implementation details

Example: Basic Class and Object

#include <iostream>
using namespace std;
 
// Class definition (blueprint)
class Car {
public:
    string brand;
    int speed;
 
    void display() {
        cout << "Brand: " << brand << ", Speed: " << speed << " km/h" << endl;
    }
};
 
int main() {
    Car myCar;           // Object creation
    myCar.brand = "Toyota";
    myCar.speed = 120;
    myCar.display();     // Output: Brand: Toyota, Speed: 120 km/h
    return 0;
}

Procedural vs OOP

// Procedural approach
void displayStudent(string name, int age) {
    cout << name << " - " << age << endl;
}
 
// OOP approach
class Student {
public:
    string name;
    int age;
    void display() {
        cout << name << " - " << age << endl;
    }
};

2. Advantages of OOP

1. Reusability (via Inheritance)

class Animal {
public:
    void breathe() {
        cout << "Breathing..." << endl;
    }
};
 
class Dog : public Animal {   // Dog inherits Animal
public:
    void bark() {
        cout << "Woof!" << endl;
    }
};
 
int main() {
    Dog d;
    d.breathe();  // Inherited from Animal
    d.bark();     // Dog's own method
    return 0;
}

2. Encapsulation (Data Hiding)

class BankAccount {
private:
    double balance;   // Hidden from outside
 
public:
    void deposit(double amount) {
        if (amount > 0) balance += amount;
    }
    double getBalance() {
        return balance;
    }
};

3. Polymorphism

class Shape {
public:
    virtual void draw() {
        cout << "Drawing a shape" << endl;
    }
};
 
class Circle : public Shape {
public:
    void draw() override {
        cout << "Drawing a Circle" << endl;
    }
};
 
class Rectangle : public Shape {
public:
    void draw() override {
        cout << "Drawing a Rectangle" << endl;
    }
};

Summary of Advantages

  • Modularity – Code is divided into objects, easier to manage
  • Reusability – Classes can be reused across programs
  • Scalability – Easy to add new features
  • Maintainability – Bugs are easier to locate and fix
  • Security – Data hiding via encapsulation

3. Input-Output in C++

C++ uses streams for I/O. The standard streams are:

StreamObjectPurpose
InputcinRead from keyboard
OutputcoutPrint to screen
ErrorcerrPrint error messages
LogclogPrint log messages

Basic I/O Example

#include <iostream>
using namespace std;
 
int main() {
    int age;
    string name;
 
    cout << "Enter your name: ";
    cin >> name;
 
    cout << "Enter your age: ";
    cin >> age;
 
    cout << "Hello, " << name << "! You are " << age << " years old." << endl;
    return 0;
}

Reading Strings with Spaces

#include <iostream>
#include <string>
using namespace std;
 
int main() {
    string fullName;
    cout << "Enter full name: ";
    getline(cin, fullName);   // reads entire line including spaces
    cout << "Name: " << fullName << endl;
    return 0;
}

Formatting Output

#include <iostream>
#include <iomanip>    // for setw, setprecision
using namespace std;
 
int main() {
    double pi = 3.14159265;
 
    cout << fixed << setprecision(2) << pi << endl;   // 3.14
    cout << setw(10) << "Hello" << endl;              // right-aligned in 10 chars
    cout << left << setw(10) << "Hello" << endl;      // left-aligned
    cout << "\n";    // newline
 
    // Multiple values
    cout << "Sum: " << 5 + 3 << endl;
    return 0;
}

Escape Sequences

EscapeMeaning
\nNewline
\tTab
\\Backslash
\"Double quote
\0Null character

4. Tokens

A token is the smallest meaningful unit in a C++ program. Every C++ program is made up of tokens.

Types of Tokens

C++ Tokens
├── Keywords      (int, float, class, return)
├── Identifiers   (myVar, studentName, total)
├── Literals      (42, 3.14, 'A', "Hello")
├── Operators     (+, -, *, /, ==, &&)
├── Punctuators   ({ } ( ) ; , . ->)
└── Comments      (// single line, /* multi-line */)

Example Showing All Token Types

#include <iostream>    // preprocessor directive
using namespace std;
 
int main() {           // int=keyword, main=identifier, ()=punctuator
    int x = 10;        // int=keyword, x=identifier, ==operator, 10=literal
    int y = 20;
    int sum = x + y;   // +=operator
    cout << sum;       // cout=identifier, <<= operator
    return 0;          // return=keyword, 0=literal
}

5. Keywords

Keywords are reserved words that have predefined meanings in C++. They cannot be used as variable names.

Complete List of C++ Keywords

alignas     alignof     and         and_eq      asm
auto        bitand      bitor       bool        break
case        catch       char        char8_t     char16_t
char32_t    class       compl       concept     const
consteval   constexpr   constinit   const_cast  continue
co_await    co_return   co_yield    decltype    default
delete      do          double      dynamic_cast else
enum        explicit    export      extern      false
float       for         friend      goto        if
inline      int         long        mutable     namespace
new         noexcept    not         not_eq      nullptr
operator    or          or_eq       private     protected
public      register    reinterpret_cast        requires
return      short       signed      sizeof      static
static_assert           static_cast struct      switch
template    this        thread_local            throw
true        try         typedef     typeid      typename
union       unsigned    using       virtual     void
volatile    wchar_t     while       xor         xor_eq

Common Keywords with Examples

#include <iostream>
using namespace std;
 
int main() {
    // Data type keywords
    int a = 5;
    float b = 3.14f;
    double c = 3.14159;
    char ch = 'A';
    bool flag = true;
 
    // Control keywords
    if (a > 0) {
        cout << "Positive" << endl;
    } else {
        cout << "Non-positive" << endl;
    }
 
    // Loop keyword
    for (int i = 0; i < 3; i++) {
        cout << i << " ";
    }
    cout << endl;
 
    // return keyword
    return 0;
}

6. Identifiers

An identifier is a name given to variables, functions, classes, objects, etc.

Rules for Identifiers

✅ VALID Rules:
1. Must start with a letter (a-z, A-Z) or underscore (_)
2. Can contain letters, digits (0-9), and underscores
3. Cannot be a keyword
4. Case-sensitive (myVar ≠ MyVar ≠ MYVAR)
5. No special characters (no space, @, #, $, etc.)
6. No limit on length (but first 31 chars are significant)

Valid vs Invalid Identifiers

// ✅ Valid identifiers
int age;
float _price;
double totalAmount;
string firstName;
int myVar123;
int MAX_SIZE;
 
// ❌ Invalid identifiers
// int 2name;       // starts with digit
// float my-var;    // hyphen not allowed
// double int;      // 'int' is a keyword
// char first name; // space not allowed
// bool @flag;      // special character

Naming Conventions

// camelCase (most common in C++)
int studentAge;
void calculateTotal();
 
// PascalCase (for classes)
class StudentRecord {};
class BankAccount {};
 
// snake_case
int student_age;
void calculate_total();
 
// ALL_CAPS (for constants)
const int MAX_SIZE = 100;
const double PI = 3.14159;

7. Data Types in C++

Data types define what kind of value a variable can hold and how much memory it occupies.

Fundamental Data Types

#include <iostream>
#include <climits>    // for INT_MAX, etc.
#include <cfloat>     // for FLT_MAX, etc.
using namespace std;
 
int main() {
    // Integer types
    int a = 42;                    // 4 bytes, -2B to +2B
    short s = 100;                 // 2 bytes
    long l = 1000000L;             // 4 or 8 bytes
    long long ll = 9000000000LL;   // 8 bytes
 
    // Floating point types
    float f = 3.14f;               // 4 bytes, ~7 decimal digits
    double d = 3.14159265358979;   // 8 bytes, ~15 decimal digits
    long double ld = 3.14159265358979323846L; // 10-16 bytes
 
    // Character type
    char c = 'A';                  // 1 byte, ASCII value 65
    wchar_t wc = L'Ω';            // wide character
 
    // Boolean type
    bool b = true;                 // 1 byte, true(1) or false(0)
 
    // Display sizes
    cout << "int: " << sizeof(int) << " bytes" << endl;
    cout << "float: " << sizeof(float) << " bytes" << endl;
    cout << "double: " << sizeof(double) << " bytes" << endl;
    cout << "char: " << sizeof(char) << " bytes" << endl;
    cout << "bool: " << sizeof(bool) << " bytes" << endl;
 
    return 0;
}

Data Type Size & Range Table

TypeSizeRange
char1 byte-128 to 127
unsigned char1 byte0 to 255
short2 bytes-32,768 to 32,767
int4 bytes-2,147,483,648 to 2,147,483,647
long4/8 bytes-2B to +2B
long long8 bytes-9.2×10¹⁸ to 9.2×10¹⁸
float4 bytes±3.4×10³⁸
double8 bytes±1.7×10³⁰⁸
bool1 bytetrue or false

8. Derived Data Types

Derived types are built from fundamental types.

Arrays

#include <iostream>
using namespace std;
 
int main() {
    // 1D Array
    int marks[5] = {85, 90, 78, 92, 88};
 
    cout << "Marks: ";
    for (int i = 0; i < 5; i++) {
        cout << marks[i] << " ";
    }
    cout << endl;
 
    // 2D Array
    int matrix[2][3] = {
        {1, 2, 3},
        {4, 5, 6}
    };
 
    cout << "Matrix:" << endl;
    for (int i = 0; i < 2; i++) {
        for (int j = 0; j < 3; j++) {
            cout << matrix[i][j] << " ";
        }
        cout << endl;
    }
    return 0;
}

Pointers

#include <iostream>
using namespace std;
 
int main() {
    int x = 10;
    int* ptr = &x;    // ptr stores address of x
 
    cout << "Value of x: " << x << endl;
    cout << "Address of x: " << &x << endl;
    cout << "Pointer ptr holds: " << ptr << endl;
    cout << "Value at ptr: " << *ptr << endl;   // dereferencing
 
    *ptr = 20;    // changing value through pointer
    cout << "New value of x: " << x << endl;    // x is now 20
 
    return 0;
}

References

#include <iostream>
using namespace std;
 
int main() {
    int original = 100;
    int& ref = original;    // ref is an alias for original
 
    ref = 200;
    cout << "original: " << original << endl;  // 200 (changed via ref)
    cout << "ref: " << ref << endl;            // 200
 
    return 0;
}

Functions as Derived Types

#include <iostream>
using namespace std;
 
// Function definition
int add(int a, int b) {
    return a + b;
}
 
// Function pointer
int (*funcPtr)(int, int) = add;
 
int main() {
    cout << add(3, 4) << endl;         // 7
    cout << funcPtr(3, 4) << endl;     // 7 (via function pointer)
    return 0;
}

9. The void Data Type

void means “no type” or “no value”. It is used in three contexts:

1. void Return Type (function returns nothing)

#include <iostream>
using namespace std;
 
void greet(string name) {
    cout << "Hello, " << name << "!" << endl;
    // No return statement needed
}
 
void printLine() {
    cout << "-------------------" << endl;
}
 
int main() {
    greet("Alice");
    printLine();
    greet("Bob");
    return 0;
}

2. void Parameters (function takes no arguments)

void displayMenu(void) {   // 'void' in parameter = no arguments
    cout << "1. Start" << endl;
    cout << "2. Exit" << endl;
}
// Same as: void displayMenu() {}

3. void Pointer (generic pointer)

#include <iostream>
using namespace std;
 
int main() {
    int x = 42;
    float f = 3.14f;
 
    void* ptr;      // void pointer - can point to any type
 
    ptr = &x;
    cout << "int value: " << *(int*)ptr << endl;    // cast before use
 
    ptr = &f;
    cout << "float value: " << *(float*)ptr << endl;
 
    return 0;
}

10. Type Modifiers

Type modifiers alter the meaning of fundamental data types.

Four Type Modifiers

ModifierEffect
signedCan hold negative values (default for int)
unsignedOnly non-negative values (doubles positive range)
shortSmaller size (minimum 2 bytes)
longLarger size

Examples with Type Modifiers

#include <iostream>
using namespace std;
 
int main() {
    // signed (default behavior)
    signed int a = -100;
    signed int b = 100;
 
    // unsigned - no negative values
    unsigned int c = 4294967295;  // max value for 32-bit unsigned
    // unsigned int d = -1;       // ERROR or wraps around
 
    // short
    short int s = 32767;    // max for short
    unsigned short us = 65535;
 
    // long
    long int li = 2147483647L;
    unsigned long ul = 4294967295UL;
 
    // long long
    long long ll = 9223372036854775807LL;
    unsigned long long ull = 18446744073709551615ULL;
 
    cout << "signed int: " << a << ", " << b << endl;
    cout << "unsigned int max: " << c << endl;
    cout << "short max: " << s << endl;
    cout << "long long max: " << ll << endl;
 
    // char modifiers
    char ch1 = -128;          // signed char: -128 to 127
    unsigned char ch2 = 255;  // unsigned char: 0 to 255
 
    cout << "signed char: " << (int)ch1 << endl;
    cout << "unsigned char: " << (int)ch2 << endl;
 
    return 0;
}

Size Comparison

#include <iostream>
using namespace std;
 
int main() {
    cout << "short: " << sizeof(short) << " bytes" << endl;
    cout << "int: " << sizeof(int) << " bytes" << endl;
    cout << "long: " << sizeof(long) << " bytes" << endl;
    cout << "long long: " << sizeof(long long) << " bytes" << endl;
    return 0;
}

11. Typecasting

Typecasting converts a value from one data type to another.

Implicit (Automatic) Typecasting

#include <iostream>
using namespace std;
 
int main() {
    int i = 10;
    double d = i;    // int → double (widening, safe)
    cout << d << endl;   // 10.0
 
    double pi = 3.14;
    int truncated = pi;  // double → int (narrowing, loses decimal)
    cout << truncated << endl;  // 3 (not 3.14!)
 
    // Arithmetic promotion
    int a = 5;
    double b = 2.5;
    double result = a + b;   // a is promoted to double temporarily
    cout << result << endl;  // 7.5
 
    return 0;
}

Explicit (C-style) Typecasting

#include <iostream>
using namespace std;
 
int main() {
    double d = 9.99;
    int i = (int)d;            // C-style cast
    cout << i << endl;          // 9
 
    int a = 7, b = 2;
    double result = (double)a / b;   // without cast: 3 (integer division)
    cout << result << endl;          // 3.5
 
    char c = 'A';
    int ascii = (int)c;
    cout << ascii << endl;      // 65
 
    int num = 65;
    char letter = (char)num;
    cout << letter << endl;     // A
 
    return 0;
}

C++ Style Casts (Modern & Preferred)

#include <iostream>
using namespace std;
 
int main() {
    double pi = 3.14159;
 
    // static_cast - compile-time conversion (most common)
    int a = static_cast<int>(pi);
    cout << a << endl;    // 3
 
    // reinterpret_cast - low-level bit reinterpretation
    int x = 65;
    char* cp = reinterpret_cast<char*>(&x);
 
    // const_cast - removes const qualifier
    const int val = 100;
    int* ptr = const_cast<int*>(&val);
 
    // dynamic_cast - safe downcasting in inheritance (runtime check)
    // Used with polymorphic classes (covered in OOP)
 
    return 0;
}

Practical Typecasting Example

#include <iostream>
using namespace std;
 
int main() {
    int total = 150;
    int count = 4;
 
    // Without cast: integer division
    cout << "Without cast: " << total / count << endl;     // 37
 
    // With cast: proper division
    cout << "With cast: " << (double)total / count << endl; // 37.5
 
    // Percentage calculation
    int marks = 450;
    int maxMarks = 500;
    double percentage = (double)marks / maxMarks * 100;
    cout << "Percentage: " << percentage << "%" << endl;   // 90%
 
    return 0;
}

12. Constants

Constants are values that cannot be changed after being set.

Using const Keyword

#include <iostream>
using namespace std;
 
int main() {
    const double PI = 3.14159265;
    const int MAX_STUDENTS = 60;
    const string COLLEGE = "ABC College";
 
    cout << "PI = " << PI << endl;
    cout << "Max students = " << MAX_STUDENTS << endl;
 
    // PI = 3.0;  // ERROR: cannot modify a const variable
 
    // Const in calculations
    double radius = 5.0;
    double area = PI * radius * radius;
    cout << "Area = " << area << endl;
 
    return 0;
}

Using #define Preprocessor Directive

#include <iostream>
#define PI 3.14159
#define MAX 100
#define GREETING "Hello, World!"
 
using namespace std;
 
int main() {
    double r = 7.0;
    cout << "Area = " << PI * r * r << endl;
    cout << "Max = " << MAX << endl;
    cout << GREETING << endl;
    return 0;
}

Using constexpr (C++11 and later)

#include <iostream>
using namespace std;
 
constexpr int SQUARE(int x) { return x * x; }
constexpr double CIRCLE_AREA(double r) { return 3.14159 * r * r; }
 
int main() {
    constexpr int side = 5;
    constexpr int area = SQUARE(side);   // computed at compile time!
    cout << "Square area: " << area << endl;    // 25
 
    constexpr double circleArea = CIRCLE_AREA(3.0);
    cout << "Circle area: " << circleArea << endl;
 
    return 0;
}

Types of Literals (Constant Values)

#include <iostream>
using namespace std;
 
int main() {
    // Integer literals
    int decimal = 255;       // decimal
    int octal = 0377;        // octal (prefix 0)
    int hexadecimal = 0xFF;  // hex (prefix 0x)
    int binary = 0b11111111; // binary (prefix 0b, C++14)
 
    // Floating literals
    float f = 3.14f;
    double d = 3.14;
    double sci = 2.5e3;      // 2500.0 (scientific notation)
 
    // Character literals
    char c1 = 'A';
    char c2 = '\n';   // escape sequence
    char c3 = '\65';  // octal ASCII
 
    // String literals
    string s1 = "Hello";
    string s2 = "Line1\nLine2";  // with escape
 
    // Boolean literals
    bool t = true;
    bool f2 = false;
 
    cout << decimal << " " << octal << " " << hexadecimal << endl; // 255 255 255
    return 0;
}

13. Operators

Operators perform operations on variables and values.

Arithmetic Operators

#include <iostream>
using namespace std;
 
int main() {
    int a = 15, b = 4;
 
    cout << "a + b = " << a + b << endl;   // 19 (addition)
    cout << "a - b = " << a - b << endl;   // 11 (subtraction)
    cout << "a * b = " << a * b << endl;   // 60 (multiplication)
    cout << "a / b = " << a / b << endl;   // 3  (integer division)
    cout << "a % b = " << a % b << endl;   // 3  (modulus/remainder)
 
    double x = 15.0, y = 4.0;
    cout << "x / y = " << x / y << endl;   // 3.75 (float division)
 
    return 0;
}

Relational (Comparison) Operators

#include <iostream>
using namespace std;
 
int main() {
    int a = 10, b = 20;
 
    cout << (a == b) << endl;   // 0 (false) - equal to
    cout << (a != b) << endl;   // 1 (true)  - not equal to
    cout << (a < b) << endl;    // 1 (true)  - less than
    cout << (a > b) << endl;    // 0 (false) - greater than
    cout << (a <= b) << endl;   // 1 (true)  - less than or equal
    cout << (a >= b) << endl;   // 0 (false) - greater than or equal
 
    return 0;
}

Logical Operators

#include <iostream>
using namespace std;
 
int main() {
    bool a = true, b = false;
 
    cout << (a && b) << endl;   // 0 (false) - AND: both must be true
    cout << (a || b) << endl;   // 1 (true)  - OR: at least one true
    cout << (!a) << endl;       // 0 (false) - NOT: flips the value
    cout << (!b) << endl;       // 1 (true)
 
    // Practical example
    int age = 25;
    bool hasLicense = true;
 
    if (age >= 18 && hasLicense) {
        cout << "Can drive!" << endl;
    }
 
    return 0;
}

Bitwise Operators

#include <iostream>
using namespace std;
 
int main() {
    int a = 12;   // binary: 1100
    int b = 10;   // binary: 1010
 
    cout << (a & b) << endl;    // 8  (1000) - AND
    cout << (a | b) << endl;    // 14 (1110) - OR
    cout << (a ^ b) << endl;    // 6  (0110) - XOR
    cout << (~a) << endl;       // -13       - NOT (complement)
    cout << (a << 1) << endl;   // 24 (11000) - Left shift
    cout << (a >> 1) << endl;   // 6  (0110) - Right shift
 
    return 0;
}

Assignment Operators

#include <iostream>
using namespace std;
 
int main() {
    int x = 10;
 
    x += 5;   cout << x << endl;  // 15  (x = x + 5)
    x -= 3;   cout << x << endl;  // 12  (x = x - 3)
    x *= 2;   cout << x << endl;  // 24  (x = x * 2)
    x /= 4;   cout << x << endl;  // 6   (x = x / 4)
    x %= 4;   cout << x << endl;  // 2   (x = x % 4)
    x <<= 2;  cout << x << endl;  // 8   (x = x << 2)
    x >>= 1;  cout << x << endl;  // 4   (x = x >> 1)
    x &= 3;   cout << x << endl;  // 0   (x = x & 3)
    x |= 5;   cout << x << endl;  // 5   (x = x | 5)
    x ^= 3;   cout << x << endl;  // 6   (x = x ^ 3)
 
    return 0;
}

Increment / Decrement Operators

#include <iostream>
using namespace std;
 
int main() {
    int a = 5;
 
    cout << a++ << endl;  // 5  (post-increment: use first, then increment)
    cout << a << endl;    // 6
 
    cout << ++a << endl;  // 7  (pre-increment: increment first, then use)
    cout << a << endl;    // 7
 
    cout << a-- << endl;  // 7  (post-decrement)
    cout << a << endl;    // 6
 
    cout << --a << endl;  // 5  (pre-decrement)
 
    return 0;
}

Ternary (Conditional) Operator

#include <iostream>
using namespace std;
 
int main() {
    int a = 10, b = 20;
 
    // Syntax: condition ? value_if_true : value_if_false
    int max = (a > b) ? a : b;
    cout << "Max = " << max << endl;   // 20
 
    string result = (a % 2 == 0) ? "Even" : "Odd";
    cout << a << " is " << result << endl;   // 10 is Even
 
    // Nested ternary
    int num = 0;
    string sign = (num > 0) ? "Positive" : (num < 0) ? "Negative" : "Zero";
    cout << sign << endl;   // Zero
 
    return 0;
}

sizeof Operator

#include <iostream>
using namespace std;
 
int main() {
    cout << sizeof(int) << endl;       // 4
    cout << sizeof(double) << endl;    // 8
    cout << sizeof(char) << endl;      // 1
    cout << sizeof(bool) << endl;      // 1
 
    int arr[10];
    cout << sizeof(arr) << endl;       // 40 (10 * 4)
    cout << sizeof(arr)/sizeof(arr[0]) << endl;  // 10 (array length)
 
    return 0;
}

14. Precedence of Operators

Operator precedence determines the order of evaluation. Higher precedence = evaluated first.

Precedence Table (High to Low)

PrecedenceOperatorsAssociativity
1 (highest)::Left to right
2() [] -> .Left to right
3++ -- (postfix)Left to right
4++ -- (prefix) ! ~ + - * & sizeofRight to left
5.* ->*Left to right
6* / %Left to right
7+ -Left to right
8<< >>Left to right
9< <= > >=Left to right
10== !=Left to right
11&Left to right
12^Left to right
13|Left to right
14&&Left to right
15||Left to right
16?:Right to left
17= += -= etc.Right to left
18 (lowest),Left to right

Examples

#include <iostream>
using namespace std;
 
int main() {
    // Arithmetic precedence: * before +
    int result = 2 + 3 * 4;
    cout << result << endl;    // 14 (not 20)
 
    // Use parentheses to override
    result = (2 + 3) * 4;
    cout << result << endl;    // 20
 
    // Mixed operators
    int a = 5, b = 3, c = 2;
    int x = a + b * c - a / c;
    // = 5 + (3*2) - (5/2)
    // = 5 + 6 - 2
    // = 9
    cout << x << endl;    // 9
 
    // Comparison vs arithmetic
    bool check = 5 + 3 > 4 * 2;
    // = (5+3) > (4*2)
    // = 8 > 8
    // = false
    cout << check << endl;    // 0
 
    // Logical operators
    bool result2 = true || false && false;
    // = true || (false && false)  [&& has higher precedence]
    // = true || false
    // = true
    cout << result2 << endl;  // 1
 
    return 0;
}

Associativity Example

#include <iostream>
using namespace std;
 
int main() {
    // Left-to-right associativity (arithmetic)
    int x = 10 - 3 - 2;
    // = (10 - 3) - 2 = 5
    cout << x << endl;   // 5
 
    // Right-to-left (assignment)
    int a, b, c;
    a = b = c = 7;   // c=7 first, then b=7, then a=7
    cout << a << " " << b << " " << c << endl;   // 7 7 7
 
    return 0;
}

15. Strings in C++

C++ supports strings in two ways: C-style strings and std::string.

C-Style Strings (char arrays)

#include <iostream>
#include <cstring>   // for strlen, strcpy, strcat, strcmp
using namespace std;
 
int main() {
    char str1[20] = "Hello";
    char str2[] = "World";
 
    cout << str1 << endl;               // Hello
    cout << strlen(str1) << endl;       // 5 (length)
 
    // String copy
    char dest[20];
    strcpy(dest, str1);
    cout << dest << endl;               // Hello
 
    // String concatenation
    strcat(str1, " World");
    cout << str1 << endl;               // Hello World
 
    // String comparison
    int result = strcmp("apple", "apple");
    cout << result << endl;             // 0 (equal)
    result = strcmp("apple", "banana");
    cout << result << endl;             // negative (apple < banana)
 
    return 0;
}
#include <iostream>
#include <string>
using namespace std;
 
int main() {
    string s1 = "Hello";
    string s2 = "World";
 
    // Concatenation
    string s3 = s1 + " " + s2;
    cout << s3 << endl;              // Hello World
 
    // Length
    cout << s3.length() << endl;     // 11
    cout << s3.size() << endl;       // 11 (same as length)
 
    // Access characters
    cout << s3[0] << endl;           // H
    cout << s3.at(6) << endl;        // W
 
    // Substring
    cout << s3.substr(6, 5) << endl; // World (start=6, length=5)
 
    // Find
    int pos = s3.find("World");
    cout << pos << endl;             // 6
 
    // Replace
    s3.replace(6, 5, "C++");
    cout << s3 << endl;              // Hello C++
 
    // Compare
    string a = "hello", b = "hello";
    cout << (a == b) << endl;        // 1 (true)
 
    // Empty check
    string empty = "";
    cout << empty.empty() << endl;   // 1 (true)
 
    // Insert
    s1.insert(5, " Beautiful");
    cout << s1 << endl;              // Hello Beautiful
 
    // Erase
    s1.erase(5, 10);
    cout << s1 << endl;              // Hello
 
    // Convert to uppercase (manual)
    for (char& c : s1) {
        c = toupper(c);
    }
    cout << s1 << endl;              // HELLO
 
    return 0;
}

String Input Methods

#include <iostream>
#include <string>
using namespace std;
 
int main() {
    string word, sentence;
 
    // cin reads one word (stops at space)
    cout << "Enter a word: ";
    cin >> word;
    cin.ignore();   // clear the newline from buffer
 
    // getline reads entire line
    cout << "Enter a sentence: ";
    getline(cin, sentence);
 
    cout << "Word: " << word << endl;
    cout << "Sentence: " << sentence << endl;
 
    return 0;
}

String to Number Conversions

#include <iostream>
#include <string>
using namespace std;
 
int main() {
    // String to int
    string numStr = "42";
    int num = stoi(numStr);
    cout << num + 1 << endl;     // 43
 
    // String to double
    string dblStr = "3.14";
    double d = stod(dblStr);
    cout << d * 2 << endl;       // 6.28
 
    // Number to string
    int x = 100;
    string s = to_string(x);
    cout << s + " points" << endl;   // 100 points
 
    double pi = 3.14159;
    string piStr = to_string(pi);
    cout << piStr << endl;       // 3.141590
 
    return 0;
}

Quick Reference Summary

Compilation and Running

# Compile
g++ -o program program.cpp
 
# Compile with C++17
g++ -std=c++17 -o program program.cpp
 
# Compile and run
g++ -o program program.cpp && ./program

Basic C++ Program Structure

#include <iostream>      // Header file
using namespace std;     // Standard namespace
 
int main() {             // Main function (entry point)
    // Your code here
    return 0;            // Success indicator
}

Common Header Files

HeaderPurpose
<iostream>cin, cout
<string>string class
<cmath>sqrt, pow, abs, sin, cos
<cstring>C-style string functions
<iomanip>setw, setprecision
<climits>INT_MAX, INT_MIN
<cfloat>FLT_MAX, DBL_MAX
<vector>dynamic arrays
<algorithm>sort, find, etc.

End of Unit 1.0 — Introduction to C++ Notes