Chapter 1 — Fundamentals of C++

INT1339 — C++ Programming Language ·

Textbook: Nguyen Duy Phuong & Nguyen Manh Son, 2020

Chapter 1 — Contents

Overview of the C++ Programming Environment

History, features, compilation vs interpretation, IDE setup

Program Structure and Execution Mechanism

Code anatomy, 4 compilation stages, 3 error types, Debugging

Language Components and Basic Syntax

Variables, data types, operators, I/O, control structures

Data Processing and Memory Management

Numbers & cmath, 1D/2D arrays, character strings, Pointers & dynamic memory

Chapter 1 Summary

Summary table + Workshop MiniPOS v0.1

Objectives

Understand C++ History & Features

Multi-paradigm, compiled, high performance, real-world applications

Master the Compilation Process

Preprocessor → Compiler → Assembler → Linker

Use Basic Syntax Proficiently

Variables, data types, operators, cin/cout, if/else, switch, loops

Manage Data & Memory

1D/2D arrays, std::string, pointers (&, *), dynamic allocation (new/delete[])

Build the MiniPOS v0.1 Application

A console-based sales management application applying all Chapter 1 knowledge

Overview of the C++ Programming Environment

History of development · Key features · Compiler vs Interpreter · IDE & Hello World

History of C++ Development

From "C with Classes" at Bell Labs to the modern language C++23/C++26

www.stroustrup.com

Bjarne Stroustrup's Homepage

This is the homepage of Bjarne Stroustrup, the designer and original implementor of C++



How was C++ born?

1

1972

Dennis Ritchie created the C language at Bell Labs to write the UNIX operating system

2

1979

Bjarne Stroustrup began developing "C with Classes" at Bell Labs — combining C's performance with OOP from Simula

3

1983

Renamed to C++ (++ meaning "upgraded C"). Added virtual functions, overloading, and references

4

1985

First commercial release alongside Stroustrup's book The C++ Programming Language

5

1998

C++98 — The first ISO standard (ISO/IEC 14882:1998) is published

ISO C++ Standardization Timeline (1998–2026)

Three Programming Paradigms: Linear, Structured, and Object-Oriented

Linear Programming

Instructions are written sequentially from top to bottom, with no division into functions or modules. Simple for small problems but difficult to maintain as the program grows.

Structured Programming (Top-Down)

Divides the program into functions, decomposing large problems into sub-problems. Example "Building a House":

  • Level 1: Build House = Lay Foundation + Pour Columns + Build Walls + Roof
  • Level 2: Lay Foundation = Excavate + Reinforce + Pour Concrete
  • Level 3: Excavate Foundation = Survey + Mark Stakes + Dig + Inspect

Drawback: Data can still be freely modified by any function.

Three Programming Paradigms: Linear, Structured, and Object-Oriented

Linear Programming

#include <iostream>
using namespace std;
int main() {
    // Rectangle 1
    int length1 = 5, width1 = 10;
    int area1 = length1 * width1;
    cout << "Area 1: " << area1 << endl;

    // Rectangle 2 (Code must be rewritten/duplicated)
    int length2 = 3, width2 = 4;
    int area2 = length2 * width2;
    cout << "Area 2: " << area2 << endl;
return 0;
}

Structured Programming (Top-Down)

#include <iostream>
using namespace std;

// Function / Subroutine to calculate rectangle area
int calculateArea(int length, int width) {
    return length * width;
}

int main() {
    // Reusing the function cleanly
    cout << "Area 1: " << calculateArea(5, 10) << endl;
    cout << "Area 2: " << calculateArea(3, 4) << endl;
    return 0;
}

Programming Language Classification & Introduction to OOP

👉 C++ is a "mid-level" language — it supports OOP/Generic programming while also allowing low-level memory access (pointers, bitwise operations).

Object

Data + Methods (student1)

Class

Blueprint for creating objects (Student)

Encapsulation

Protects data through methods

Inheritance

Child class inherits from parent class

Polymorphism

Same method, different behaviors

Hello World Example

https://godbolt.org/

Key Features of C++

Multi-paradigm Language

Superior Performance

Real-world Application Ecosystem

C++ is a Multi-Paradigm Language

Procedural Programming

Organizes code into functions, executed sequentially. Example: int main(), void swap(...)

Object-Oriented Programming (OOP)

Data + methods encapsulated in a class. Example: class SinhVien { ... };

Generic Programming

Write generalized code for multiple data types. Example: template<typename T>

C++ is considered a "half object-oriented, half structured" language — it still allows free variables and free functions inherited from C.

Java/C# are pure OOP

Rust adds an ownership model that guarantees memory safety without a garbage collector.

Procedural



OOP


Generic


Performance: How Fast is C++?

Fannkuch-Redux Benchmark — A Pure Compute-Speed Test

What is Fannkuch-Redux?

  • Origin: Derived from German "Pfannkuchen" (pancake) — the act of flipping pancakes
  • Algorithm: Given a permutation of N numbers, take the first element k, reverse the first k elements, repeat until the first element is 1
  • Benchmark Goal: Generate all N! permutations (N=12 → 479,001,600 permutations), find the max flip count, maintain a checksum
  • Why it's a great benchmark: Pure compute-bound (only integer ops + array manipulation, no I/O), highly parallelizable across CPU threads

Step-by-Step Example

Initial: [4, 2, 1, 5, 3]

Step 0: [4, 2, 1, 5, 3]  → first=4 → flip first 4
Step 1: [5, 1, 2, 4, 3]  → first=5 → flip all 5
Step 2: [3, 4, 2, 1, 5]  → first=3 → flip first 3
Step 3: [2, 4, 3, 1, 5]  → first=2 → flip first 2
Step 4: [4, 2, 3, 1, 5]  → first=4 → flip first 4
Step 5: [1, 3, 2, 4, 5]  → first=1 → STOP!

Total Flips = 5

Benchmark Metrics Explained

Data source: The Computer Language Benchmarks Game (benchmarksgame-team.pages.debian.net) — N = 12 (479,001,600 permutations)

Fannkuch-Redux Benchmark Results (N=12)

What the Numbers Tell Us

Execution Speed (secs)

  • Compiled Languages (C, C++, Rust): ~8.6s–12s — compile directly to native machine code with SIMD vectorization, zero runtime interpretation overhead
  • JIT-Compiled Languages (Java, C#): ~18s–19s — roughly 1.7× – 2.1× slower than C++
  • Dynamic / Interpreted (Node.js, Python): Node.js ~90s (10× slower); Python 3 ~9 min (62×) to ~40 min (278×) slower

Threading Efficiency (cpu load)

  • Multi-threaded C++ #5: 10.61s wall-clock, 41.90s total CPU — all 4 cores at ~100%
  • Single-threaded C++ #7: 25.36s wall-clock, 25.35s total CPU — only 1 core active
  • Takeaway: Proper multi-threading delivers ~2.4× speedup within the same language and compiler

Memory Footprint (mem)

  • C / C++ / Rust: ~1 MB – 2.3 MB — manual memory management, no GC metadata
  • Java / C# / Node.js: ~31 MB – 33 MB — JVM/V8 runtime + Garbage Collector overhead
  • C++ single-thread variant: only 852 KB — the most memory-efficient C++ implementation

Where is C++ being used? (2024–2025)

🎮 Game Engine

Unreal Engine 5 (Epic Games) — used for Fortnite, Final Fantasy VII Remake

🖥️ Operating Systems

Windows, Linux Kernel — low-level hardware control

🏦 HFT Finance

Bloomberg Terminal — processes hundreds of billions of market ticks/day

🤖 AI/ML Backend

TensorFlow & PyTorch — Python frontend, C++ core for speed optimization

🌐 Web Browsers

Chrome V8 engine, Firefox — JS engines written in C++

🚀 Space Exploration

NASA Mars Rovers (Curiosity, Perseverance) — autonomous navigation control

Distinguishing C++ Development Tools: GCC, GDB, MinGW, and Dev-C++

Comparing Compiler vs. Interpreter

C++ (Compiled) — Sum of 1 to 100,000,000

Source Code (main.cpp)

#include <iostream>
using namespace std;

int main() {
    cout << "Step 1: Program starting..." << endl;

    long long sum = 0;
    for (long long i = 1; i <= 100000000; i++) {
        sum += i;
    }

    cout << "Step 2: Sum calculated = " << sum << endl;
    return 0;
}

How It Executes

Step 1 — Compilation:

Run: clang++ -O2 main.cpp -o main.exe

The compiler translates the ENTIRE source file into native machine code (main.exe) before anything runs.

Syntax Error Behavior: If line 10 has a missing semicolon, the compiler halts immediately. No .exe is created. "Step 1" will NEVER print.

Step 2 — Execution:

Run: ./main.exe

Executes machine instructions directly on the CPU.

Result: Sum = 5,000,000,050,000,000

Execution time: ~0.x seconds

Python (Interpreted) — Sum of 1 to 100,000,000

Source Code (main.py)

print("Step 1: Program starting...")

total_sum = 0
for i in range(1, 100000001):
    total_sum += i

print("Step 2: Sum calculated =", total_sum)

How It Executes

No Separate Build Step:

Run: python3 main.py

No compilation phase — the interpreter starts immediately.

Line-by-Line Execution:

  • Line 1 → prints "Step 1: Program starting..." immediately
  • Lines 3–5 → interpreter loops 100,000,000 times, checking types dynamically on every iteration
  • Line 7 → prints the final sum

Runtime Error Behavior: If line 7 had print(undefined_variable), line 1 would STILL print successfully before the program crashes on line 7.

Result: Sum = 5,000,000,050,000,000

Execution time: ~ x seconds (slower than C++ for this loop due to dynamic type checking overhead)

Compiler vs. Interpreter — Summary Takeaway

⚡ C++ (Compiler)

  • Takes time upfront to compile the whole file into native machine code
  • All syntax errors are caught before the program ever runs
  • Runs at blazing hardware speed: ~0.x s for 100M iterations
  • Best for: performance-critical systems, games, embedded, OS kernels

🐢 Python (Interpreter)

  • Starts instantly — no compilation step needed
  • Errors surface only when the interpreter reaches the bad line at runtime
  • Slower for heavy computation: ~x s for the same 100M iterations
  • Best for: rapid prototyping, scripting, data science, automation

Where does C++ stand on the programming language map?

Development Environment and First Program

Choose an IDE · Configure VS Code · Demo OnlineGDB · Analyze "Hello World" code

Integrated Development Environments (IDEs) for C++

💻 Visual Studio Code

Lightweight code editor, extensible via Extensions (C/C++ Extension Pack). Cross-platform, integrated Terminal & Git. Recommended for this course.

🧠 CLion (JetBrains)

Professional IDE with powerful code completion, integrated CMake. Free for students (register with @ptit.edu.vn email).

🪟 Visual Studio Community

Microsoft's full-featured IDE for Windows. Extremely powerful Debugger, suitable for large projects.

📦 Dev-C++ / Code::Blocks

Classic, lightweight IDEs requiring minimal configuration. Commonly used in academic competitions and exams.

Steps to Set Up C++ Environment with VS Code

1

Step 1 — Install Compiler

Windows: MinGW-w64 (g++) via MSYS2
macOS: xcode-select --install
Linux: sudo apt install build-essential g++

2

Step 2 — Install VS Code & Extensions

Download VS Code from code.visualstudio.com. Install Extensions: C/C++ (Microsoft) and Code Runner

3

Step 3 — Verify Installation

Open Terminal, type g++ --version. If a version is displayed (e.g., g++ (GCC) 13.2.0) → Installation successful!

Quick Practice with Online IDE: OnlineGDB

🌐 onlinegdb.com

An online programming tool that requires no installation. Select C++17/C++20, write your code, and press Run (F9) to compile and run directly in your browser.

  • Supports interactive cin input in the Console panel
  • Integrated Debugger (Breakpoints, Step into, Step over)
  • Perfect for quick in-class exercises

Also worth trying: godbolt.org (Compiler Explorer) lets you inspect the generated Assembly code.


Decoding the "Hello World" Program

#include <iostream>  // 1. Load I/O library

using namespace std;  // 2. Use standard namespace

int main() {          // 3. Main function - Entry point
    // 4. Output string to screen
    cout << "Hello, PTIT Multimedia!" << endl;

    return 0;         // 5. Report success to OS
}

#include <iostream>

Preprocessor loads the library to use cout, cin

using namespace std

No need to type std::cout, std::endl

int main()

Mandatory function in every C++ program. The OS always calls main() first

return 0

The value 0 signals that the program ended normally (no errors)

Buffer Overflow Attack

The Vulnerable Code

char input[8];
char password[8];

strcpy(password, "rictro");

std::cin >> input; // no bounds check!

if (strncmp(input, password, 8) == 0) {
    // Grant access
} else {
    // Deny access
}

Why Is This Dangerous?

  • 1 char = 1 byte (per C/C++ standard)
  • char input[8] occupies exactly 8 contiguous bytes in RAM
  • char password[8] occupies the NEXT 8 contiguous bytes immediately after input
  • cin >> input reads until Enter — it does NOT check if input fits in 8 bytes
  • If the user types more than 7 characters, the extra bytes spill over into adjacent memory — overwriting password!
Byte #:  0  1  2  3  4  5  6  7  | 8  9 10 11 12 13 14 15
        [      input[8]          ] [     password[8]      ]
        (user-controlled)          ("rictro\0" — secret!)

The vulnerability: std::cin >> input has NO bounds check. It reads until Enter, regardless of array size. Overflow bytes spill directly into the next variable — password.

Memory Diagrams — Normal Cases (No Overflow)

Case 1 — Correct Password: input = 'rictro' (6 chars) ✅

6 chars + null terminator fits within 8 bytes. password is unchanged.

Case 2 — Wrong Password: input = 'hello' (5 chars) ❌

5 chars + null terminator fits within 8 bytes. password is unchanged.


Case 3: Buffer Overflow Attack — 'sunshinesunshine' (16 chars)

Case 3: Buffer Overflow Attack — 'sunshinesunshine' (16 chars)

Step-by-Step Attack

  1. cin >> input starts writing at byte 0
  1. Bytes 0–7: "sunshine" fills input[8] completely — no error raised
  1. Bytes 8–15: "sunshine" continues writing past the buffer boundary — directly into password[8]!
  1. Byte 16: null terminator \0 is written past both arrays
  1. password now reads "sunshine" instead of "rictro"
  1. strncmp(input, password, 8) compares "sunshine" vs "sunshine" → match → Access granted!

Root Cause & Real-World Impact

  • std::cin >> performs NO bounds checking — it writes until whitespace or EOF, regardless of array size
  • Stack variables are laid out contiguously in memory — adjacent arrays are neighbors in RAM
  • An attacker who knows the buffer size can craft an input that overwrites adjacent variables
  • This is a classic Stack Buffer Overflow — one of the most exploited vulnerability classes in C/C++ history
  • Real-world impact: used to inject shellcode, escalate privileges, crash systems (e.g., Morris Worm 1988, Heartbleed 2014)

Fixing the Buffer Overflow

Fix 1: Use cin.width() to limit input

cin.width(8);   // Read at most 7 chars + null terminator
cin >> input;   // Now safe — won't overflow

Note: cin.width(n) tells cin to read at most n-1 characters, leaving room for \0

Fix 2: Use std::string instead of char[]

string input;   // Dynamically sized — no fixed buffer
cin >> input;   // Safe — std::string manages its own memory
if (input == password) { ... }

Note: std::string automatically resizes. No fixed-size buffer = no overflow risk.

Fix 3: Use fgets() (C-style safe read)

fgets(input, sizeof(input), stdin);
// sizeof(input) = 8 → reads at most 7 chars + \0
// Never writes past the buffer boundary

Note: fgets() always respects the size limit. The classic safe alternative to gets() (which is banned in modern C/C++).

❓ Checkpoint — Quick Knowledge Check

Question 1: Who is the author of C++?

A. Dennis Ritchie   

B. Bjarne Stroustrup   

C. James Gosling   

D. Guido van Rossum

Question 2: What type of language is C++?

A. Pure Interpreted   

B. Compiled, Multi-paradigm   

C. Scripting language   

D. Mark-up language

Question 3: Which component specifies the entry point of program execution?

A. #include <iostream>   

B. using namespace std;

C. int main()   

D. return 0;

✅ Checkpoint — Answers & Explanations

Question 1: B. Bjarne Stroustrup ✓

Stroustrup developed "C with Classes" starting in 1979 at Bell Labs, renaming it C++ in 1983. Dennis Ritchie → C; James Gosling → Java; Guido van Rossum → Python.

Question 2: B. Compiled, Multi-paradigm ✓

C++ compiles directly to machine code (Compiled) and supports all 3 programming paradigms: Procedural, OOP, and Generic.

Question 3: C. int main() ✓

The main() function is the only mandatory Entry Point of every C++ program. The operating system always calls main() first when launching the program.

Structure and Operating Mechanism of a C++ Program

Program Anatomy · 4-Step Compilation Process · Error Classification · Debugging

Basic Structure of a C++ Program

Preprocessor · Main Function · Code Blocks · Standard Coding Style

Anatomy of a C++ Source File Structure

According to the textbook: A C++ program may consist of multiple source files (.cpp, .h), but there can only be ONE single main() function.

Details: Preprocessor, Namespace & Statement

Preprocessor Directive (#include)

Starts with the # symbol. Before compilation, the Preprocessor copies the entire content of the library file (e.g., iostream) and inserts it at the exact position of the #include line.

Namespace

Resolves naming conflicts between functions/variables when merging libraries. The using namespace std; directive allows direct use of cout, cin instead of std::cout.

Statement & Block

Each statement ends with a semicolon

Simple C++ Program for Sales Invoice

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

int main() {
    string productName = "Bluetooth Headphones";
    int quantity = 2;
    double unitPrice = 450.0;

    double totalAmount = quantity * unitPrice;

    cout << "=== SALES INVOICE ===" << endl;
    cout << "Product: " << productName << endl;
    cout << "Total Amount: $" << totalAmount << endl;

    return 0;
}

Coding Conventions

  • Name variables using camelCase (e.g., tenSanPham, tongTien)
  • Use 4 spaces for indentation inside the main() function
  • Add appropriate comments: // single-line comment or /* ... */ for multi-line

Compilation and Debugging

4 Compilation Stages

3 Types of Errors

Debugging Skills

The Journey from Source Code (.cpp) to Executable File (.exe)

The C++ Compiler does not translate source code into a .exe file in a single step — it goes through 4 consecutive stages. The benefit: it enables Independent Compilation — for large codebases, only the files that have changed need to be recompiled, and the Linker then combines them into a single executable.

Details of the 4 Stages in the C++ Compilation Toolchain

3 Errors Type: Syntax, Runtime, and Logic Error

🔴Syntax Error

When: At compile time
Cause: Code violates language rules
Example: Missing ;, typing count instead of cout
Detection: Compiler highlights the specific error line in red

🟠 Runtime Error

When: While the program is executing
Cause: Memory violation / mathematical error
Example: Division by zero, accessing array out of bounds
Detection: Program crashes (Segmentation Fault)

🟡 Logic Error

When: Program runs to completion but produces WRONG results
Cause: Incorrect algorithm / formula
Example: Computing average as (a+b)/3 instead of (a+b)/2
Detection: Manually checking test cases, using a Debugger

Debugging — A Developer's Essential Survival Skill

❓ Checkpoint — Quick Review Questions

Question 1: What is the correct order of the C++ compilation process?

A. Compiler → Preprocessor → Linker → Assembler
B. Preprocessor → Compiler → Assembler → Linker
C. Linker → Assembler → Compiler → Preprocessor
D. Preprocessor → Assembler → Compiler → Linker

Question 2: Which error does NOT stop the program from compiling?

A. Missing closing curly brace {
B. Missing semicolon ;
C. Wrong formula for perimeter (a+b)*3
D. Incorrect library name #include <iostreams>

Question 3: What is the F10 shortcut used for in the VS Code Debugger?

A. Set Breakpoint    B. Run the program immediately
C. Step Over (Execute current line)    D. Step Into (Enter inside a function)

✅ Checkpoint — Answers & Explanations

Question 1: B. Preprocessor → Compiler → Assembler → Linker ✓

Preprocessor handles preprocessing → Compiler translates to Assembly → Assembler translates to Object file → Linker links with libraries to produce .exe.

Question 2: C. Wrong formula (a+b)*3 ✓

This is a Logic Error — the program still compiles successfully into .exe but produces the wrong result. Options A, B, and D are Syntax Errors that cause the compiler to stop immediately.

Question 3: C. Step Over ✓

F10 performs Step Over — executes the next line in the current function without stepping into any called functions. F9 is Breakpoint, F11 is Step Into.

Language Components and Basic Syntax

Variables & Data Types · Type Casting · Operators · Input/Output · Control Structures

Variables, Data Types and Operators

Variable Naming Rules

RAM Memory

Type Casting

Operators & Common Pitfalls

Variables — Declaration and Naming Rules

Declaration Syntax

DataType variableName = initialValue;

int age = 20;        // Integer
double gpa = 8.5;    // Floating point
char grade = 'A';    // Character
bool isApproved = true; // Boolean

A variable is a named memory cell in RAM used to store data that can change during program execution.

Variable Naming Rules

✅ Valid: Contains only letters (a-z, A-Z), digits (0-9), and underscores _. Must start with a letter or _.

❌ Invalid: Starts with a digit (1bien), contains spaces (ten bien), conflicts with C++ keywords (int, return).

💡 Recommended: Use English names following camelCase convention (e.g., studentName, totalPrice).

Basic Data Types in C++

💡 Use the sizeof(dataType) function to check the actual size: cout << sizeof(int);

Visualizing Data Types in RAM Memory

RAM Memory Cell Diagram

RAM Addresses (Example)
┌────────┬────────┬────────┬────────┐
│ 0x100  │ 0x101  │ 0x102  │ 0x103  │
│        int x = 42 (4 Bytes)       │
├────────┬────────┬────────┬────────┤
│ 0x104  │ 0x105  │ 0x106  │ 0x107  │
│ 0x108  │ 0x109  │ 0x10A  │ 0x10B  │
│     double d = 3.14 (8 Bytes)     │
├────────┴────────────────────────  │
│ 0x10C  │ char c = 'A' (1 Byte)    │
└────────┴───────────────────────── ┘

Explanation

RAM is divided into small memory cells, each with a size of 1 Byte (8 bits) and a unique memory address (in Hexadecimal format such as 0x100).

When declaring int x, C++ allocates 4 consecutive memory cells to store the number 42. When declaring double d, C++ allocates 8 consecutive memory cells.

Data Type Casting: Implicit vs Explicit Casting

Implicit Casting

int a = 5;
double b = a; // b = 5.0 (automatic)

The compiler automatically converts from a smaller type to a larger type (no data loss). Example: int → double.

Explicit Casting

int a = 5, b = 2;
// Integer division — WRONG!
double r1 = a / b;  // = 2.0

// Cast the type — CORRECT!
double r2 = static_cast<double>(a) / b; // = 2.5

The programmer actively casts the type. Old C style: (double)a. Modern C++ style (recommended): static_cast<double>(a).

Arithmetic, Increment/Decrement, Compound Assignment Operators

Arithmetic Operators

+, -, *, / (division), % (modulo — integers only!)

Example: 7 % 3 = 1 (7 divided by 3 gives 2 remainder 1)

Compound Assignment Operators

x += 5 (equivalent to x = x + 5), -=, *=, /=, %=

Increment/Decrement Operators (++, --)

int a = 5, b = 5;
int x = a++; // x = 5, a = 6
             // (use a first, then increment)
int y = ++b; // y = 6, b = 6
             // (increment b first, then use)

Comparison Operators and Logical Operators

Comparison (Relational) Operators

Return a bool value (true/false):

  • == (equal), != (not equal)
  • > (greater than), < (less than)
  • >= (greater than or equal to), <= (less than or equal to)

Logical Operators

  • && (AND — True when BOTH are true)
  • || (OR — True when AT LEAST ONE is true)
  • ! (NOT — Reverses the logical value)

Practical Example

int tuoi = 20;
bool hasStudentCard = true;

// Student discount condition: age < 22 AND has student card
bool isDiscounted = (tuoi < 22) && hasStudentCard;
// Result: true

Operator Precedence

⚠️ Common Traps with Data Types and Operators

Trap 1 — Integer Division

cout << 5 / 2;   // = 2 (NOT 2.5!)
cout << 5.0 / 2; // = 2.5 (5.0 is a double)

Trap 2 — Overflow

int maxInt = 2147483647;
cout << maxInt + 1; // = -2147483648 (Overflow!)

🔥 The Ariane 5 rocket explosion (1996): Integer overflow when converting a 64-bit floating-point number to a 16-bit integer caused ~$370 million in damages!

Trap 3 — Confusing = and ==

if (x = 3) { ... } //

Basic Input/Output (cout, cin)

Standard I/O · Input stream issues with cin.getline · Data formatting with iomanip

Standard Input/Output with std::cout and std::cin

Output (cout)

Uses the << insertion operator. Combine with endl or '\n' to add a new line.

cout << "Hello " << name
     << ", age: " << age << endl;

Input (cin)

Uses the >> extraction operator. cin automatically skips whitespace when reading numbers/words.

int age;
cout << "Enter age: ";
cin >> age;

⚠️ Input Buffer Pitfall with Strings

cin >> name; only reads until the first whitespace. Entering "Nguyen Van A" → only "Nguyen" is captured!

Fix: Use getline(cin, name);

⚠️ If a cin >> statement precedes getline, you must add cin.ignore(); to clear the Enter key from the buffer!

Formatting Output Data with the <iomanip> Library

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

int main() {
    double score = 8.56789;
    double price = 12.50;

    // 1. Float with 2 decimal places
    cout << fixed << setprecision(2);
    cout << "Score: " << score << endl;
    // Output: 8.57

    // 2. Column alignment (setw)
    cout << left  << setw(15) << "Product"
         << right << setw(10) << "Price" << endl;
    cout << left  << setw(15) << "Bread"
         << right << setw(10) << price << endl;
    return 0;
}

Manipulator Summary Table

  • fixed: Display floating-point numbers in fixed decimal notation
  • setprecision(n): Set n digits after the decimal point
  • setw(w): Set minimum display width to w characters
  • left / right: Align text left or right within the setw field

Control Structures: Branching and Loops

if-else · switch-case · Ternary Operator · for, while, do-while · break & continue

Branching Structures: if-else and switch-case

if ... else if ... else

Use for range-based conditions or complex logical expressions.

if (score >= 8.5) {
    cout << "Excellent";
} else if (score >= 7.0) {
    cout << "Good";
} else {
    cout << "Average/Pass";
}

switch ... case

Use when comparing a single integer/character variable against fixed values. ⚠️ REQUIRED to have

Ternary Operator (?:) — Compact Way to Write Simple Branches

Syntax: ConditionExpression ? ValueIfTrue : ValueIfFalse;

Regular approach (4 lines)

int maxVal;
if (a > b) {
    maxVal = a;
} else {
    maxVal = b;
}

Ternary operator (1 line)

int maxVal = (a > b) ? a : b;

// Use directly inside cout:
cout << (score >= 5.0 ? "PASSED" : "FAILED");

Loop Structures in C++

Example — do-while forcing positive number input:

int n;
do {
 cout << "Enter n > 0: ";
 cin >> n;
} while (n <= 0); // Re-prompt if input is invalid

Loop Control Statements: break and continue

The break Statement

Exits the loop COMPLETELY immediately.

for (int i = 1; i <= 10; i++) {
    if (i == 5) break;
    cout << i << " ";
}
// Output: 1 2 3 4

The continue Statement

Skips the rest of the current iteration and moves to the next one.

for (int i = 1; i <= 5; i++) {
 if (i == 3) continue;
 cout << i << " ";
}
// Output: 1 2 4 5

❓ Checkpoint — Quick Review Questions

Question 1: Given int a = 7, b = 2; → The values of a/b and a%b in C++ are respectively:

A. 3.5 and 1    B. 3 and 1    C. 3 and 3.5    D. 3.5 and 0

Question 2: When is the getline(cin, str) command used?

A. To input an integer   

B. To input a string containing spaces
C. To input a single character   

D. To print a string to the screen

Question 3: Which loop guarantees the code block executes AT LEAST ONCE?

A. for   

B. while   

C. do-while   

D. All of the above loops

✅ Checkpoint — Answers & Explanations

Question 1: B. 3 and 1 ✓

Since a and b are both int, 7/2 performs integer division and returns 3 (discarding the decimal part); 7%2 returns the remainder, which is 1.

Question 2: B. Input a string with spaces ✓

cin >> str only reads up to the first whitespace. getline(cin, str) reads the entire line of text including spaces until Enter is pressed.

Question 3: C. do-while ✓

The do-while loop executes the block of code first and then checks the condition at the end, so the block always runs at least once.

Data Processing and Memory Management

Number Processing & cmath Library

1D/2D Arrays

Strings

Pointers & Dynamic Allocation

Numeric Processing and the cmath Library

Advanced integer/floating-point types

Common mathematical functions in <cmath>

Advanced Number Handling: Signed, Unsigned & Constants

Signed vs Unsigned

unsigned int: Stores only non-negative integers (≥ 0), range 0 to 4,294,967,295. Suitable for storing array sizes (size_t).

Floating Point & Precision

float: 4 bytes. double: 8 bytes. Constants: 3.14f (float), 3.14 (double). Recommended

Common Mathematical Functions in the <cmath> Library

1D Arrays and 2D Arrays

Array Data Structure · Traversal & Basic Algorithms · 2D Array Matrices

1D Array — Declaration & Memory Storage

Declaration and Initialization

int a[5] = {10, 20, 30, 40, 50};
// a[0]=10, a[1]=20, a[2]=30, a[3]=40, a[4]=50

Contiguous Memory Layout

[ 10 ][ 20 ][ 30 ][ 40 ][ 50 ]
0x100  0x104  0x108  0x10C  0x110
 a[0]   a[1]   a[2]   a[3]   a[4]
(Each int occupies 4 bytes)

⚠️ Critical Characteristics of C++ Arrays

Array indices always start from 0 to N−1 (where N is the size of the array).

No Out-of-Bounds Checking: Accessing a[5] or a[10] will NOT be caught by the compiler — it will read/write into garbage memory → causing crashes or security vulnerabilities!

An array is a collection of elements of the SAME DATA TYPE, stored in CONTIGUOUS MEMORY CELLS in RAM.

Basic Operations on 1D Arrays

Array Traversal & Sum Calculation

int sum = 0;
for (int i = 0; i < n; i++) {
    sum += a[i];
}

Linear Search & Find Max/Min

int maxVal = a[0];
for (int i = 1; i < n; i++) {
    if (a[i] > maxVal)
        maxVal = a[i];
}

Bubble Sort

for (int i = 0; i < n-1; i++) {
 for (int j = 0; j < n-i-1; j++) {
 if (a[j] > a[j+1])
 swap(a[j], a[j+1]);
 }
}

2D Array — Matrix Model

Declaring a 2×3 Matrix

int matrix[2][3] = {
    {1, 2, 3},  // Row 0
    {4, 5, 6}   // Row 1
};

Traversal with 2 Nested for Loops

for (int i = 0; i < 2; i++) {
  for (int j = 0; j < 3; j++) {
    cout << matrix[i][j] << " ";
  }
  cout << endl;
}

Visual Representation

Table Model (2x3):
 Col 0  Col 1  Col 2
Row 0  [ 1 ]  [ 2 ]  [ 3 ]
Row 1  [ 4 ]  [ 5 ]  [ 6 ]

Stored in RAM (Row-major order):
┌───┬───┬───┬───┬───┬───┐
│ 1 │ 2 │ 3 │ 4 │ 5 │ 6 │
└───┴───┴───┴───┴───┴───┘
[ Row 0 ]  [ Row 1 ]

Character Strings (C-string vs std::string)

C-style strings (char[]) vs C++ string objects (std::string) & String handling methods

Strings: C-string (char[]) vs std::string

String Manipulation Methods with std::string

#include <string>
string s = "PTIT Academy";

// 1. String length
cout << s.length();    // 12

// 2. Check if empty
if (s.empty()) cout << "Empty!";

// 3. Concatenation
s += " Multimedia";

// 4. Character access
char c = s[0];          // 'P'

// 5. Extract substring
string sub = s.substr(0, 4); // "PTIT"

// 6. Find substring position
size_t pos = s.find("PTIT"); // 0

Practical Application: Normalize Full Name

string name = " john DOE ";
string formatted = "";
bool isNewWord = true;

for (char c : name) {
 if (c != ' ') {
 if (isNewWord) {
 formatted += toupper(c);
 isNewWord = false;
 } else {
 formatted += tolower(c);
 }
 } else if (!isNewWord) {
 formatted += ' ';
 isNewWord = true;
 }
}
// Output: "John Doe"

Pointers and Dynamic Memory Management

Memory Address

Operators & and *

Arrays & Pointers

Heap Allocation (new/delete[])

Avoiding Memory Leaks

Pointer — Concepts and &, * Operators

int x = 42;
int* ptr = &x; // ptr stores the address of x

cout << x;    // 42   (Value of x)
cout << &x;   // 0x7fff5a2 (Address of x)
cout << ptr;  // 0x7fff5a2 (Value of ptr)
cout << *ptr; // 42   (Value at the address ptr points to)

*ptr = 100;   // Change x THROUGH the pointer!
cout << x;    // 100  (x has been updated!)

Two Important Operators

& (Address-of operator): Gets the memory address of a variable. Example: &x returns the RAM address of x.

* (Dereference operator): Accesses the value at the address the pointer is pointing to — reads or modifies it.

Pointer — Visual Representation in RAM

Variable  Value     RAM Address
┌──────┬─────────┬────────────┐
│  x   │   42    │  0x1000    │ ◄──┐
├──────┼─────────┼────────────┤    │
│ ptr  │ 0x1000  │  0x2000    │ ───┘
└──────┴─────────┴────────────┘
(ptr holds value 0x1000 → Points to x)

Operations:
- ptr = &x  → ptr stores address 0x1000
- *ptr      → "Go to 0x1000, read value" → 42
- *ptr = 100 → "Go to 0x1000, write 100" → x = 100

Real-world Analogy

A pointer is like a piece of paper with a home address written on it. The paper (ptr) is not the house (x), but holding the paper you can find your way to the house and change the furniture inside.

The Intimate Relationship Between Pointers and Arrays

int arr[5] = {10, 20, 30, 40, 50};

// Array name = Address of the first element
cout << arr;      // 0x1000
cout << &arr[0];  // 0x1000 (Identical!)

// Pointer Arithmetic:
int* ptr = arr;   // ptr points to arr[0]
cout << *ptr;     // 10 (arr[0])
cout << *(ptr+1); // 20 (arr[1])
cout << *(ptr+2); // 30 (arr[2])

// Two equivalent ways to access elements:
// arr[i]  ⟺  *(arr + i)

Pointer Arithmetic Diagram

ptr ──► [10][20][30][40][50]
        ptr  ptr+1 ptr+2 ptr+3 ptr+4

In C++, an array name is a constant pointer that points to the first element of the array (&arr[0]).

When you add 1 to a pointer (ptr+1), the address increases by sizeof(int) = 4 bytes, not by 1 byte.

Dynamic Memory Allocation on the Heap (new / delete[])

int n;
cout << "Enter number of elements n: ";
cin >> n;

int* arr = new int[n]; // 1. Allocate n elements on the Heap
for (int i = 0; i < n; i++) cin >> arr[i]; // 2. Use like a normal array

delete[] arr; // 3. MUST free memory!
arr = nullptr; // 4. Assign nullptr to avoid Dangling Pointer

⚠️ 4 Dangerous Errors When Working with Pointers & Memory

1. Memory Leak

void memoryLeak() {
  int* p = new int[1000]; // Allocates 4KB RAM
  // Forgot delete[] p → Leaks 4KB every call!
}

🔥 An online game with a Memory Leak will drain all RAM and cause lag after a few hours of play!

2. Dangling Pointer

int* p = new int(42);
delete p; // Free the memory
cout << *p; //

❓ Checkpoint — Quick Knowledge Check

Question 1: Given int arr[5] = {1,2,3,4,5}; → What is the value of *(arr+3)?

A. 3    B. 4    C. 5    D. The address of arr[3]

Question 2: What does the & operator placed before a variable name (e.g. &x) do?

A. Gets the value of x    B. Gets the memory address of x
C. Logical AND operation    D. Frees the variable x

Question 3: After executing delete[] arr;, what is the best programming practice?

A. Do nothing    B. Assign arr = nullptr;
C. Call free(arr); afterwards    D. Redeclare int arr;

✅ Checkpoint — Answers & Explanations

Question 1: B. 4 ✓

arr points to arr[0]. The expression *(arr+3) is equivalent to arr[3], returning the element at index 3 (the 4th element) which has the value 4.

Question 2: B. Get the memory address of x ✓

The & operator (Address-of operator) retrieves the RAM memory address of variable x. The * operator is used to dereference and get the value.

Question 3: B. Assign arr = nullptr; ✓

Assigning nullptr after delete eliminates the risk of a Dangling Pointer. If *arr is accidentally accessed when arr == nullptr, the program throws a clear error instead of silently causing Undefined Behavior.

Chapter 1 Summary & MiniPOS v0.1 Workshop

Chapter 1 Knowledge Review · Building the MiniPOS v0.1 Application · Homework Assignment