INT1339 — C++ Programming Language ·
History, features, compilation vs interpretation, IDE setup
Code anatomy, 4 compilation stages, 3 error types, Debugging
Variables, data types, operators, I/O, control structures
Numbers & cmath, 1D/2D arrays, character strings, Pointers & dynamic memory
Summary table + Workshop MiniPOS v0.1
Multi-paradigm, compiled, high performance, real-world applications
Preprocessor → Compiler → Assembler → Linker
Variables, data types, operators, cin/cout, if/else, switch, loops
1D/2D arrays, std::string, pointers (&, *), dynamic allocation (new/delete[])
A console-based sales management application applying all Chapter 1 knowledge
History of development · Key features · Compiler vs Interpreter · IDE & Hello World
Dennis Ritchie created the C language at Bell Labs to write the UNIX operating system
Bjarne Stroustrup began developing "C with Classes" at Bell Labs — combining C's performance with OOP from Simula
Renamed to C++ (++ meaning "upgraded C"). Added virtual functions, overloading, and references
First commercial release alongside Stroustrup's book The C++ Programming Language
C++98 — The first ISO standard (ISO/IEC 14882:1998) is published
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.
Divides the program into functions, decomposing large problems into sub-problems. Example "Building a House":
Drawback: Data can still be freely modified by any function.
#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;
}#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;
}👉 C++ is a "mid-level" language — it supports OOP/Generic programming while also allowing low-level memory access (pointers, bitwise operations).
Data + Methods (student1)
Blueprint for creating objects (Student)
Protects data through methods
Child class inherits from parent class
Same method, different behaviors
https://godbolt.org/
Multi-paradigm Language
Superior Performance
Real-world Application Ecosystem
Organizes code into functions, executed sequentially. Example: int main(), void swap(...)
Data + methods encapsulated in a class. Example: class SinhVien { ... };
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.



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 = 5Data source: The Computer Language Benchmarks Game (benchmarksgame-team.pages.debian.net) — N = 12 (479,001,600 permutations)
Unreal Engine 5 (Epic Games) — used for Fortnite, Final Fantasy VII Remake
Windows, Linux Kernel — low-level hardware control
Bloomberg Terminal — processes hundreds of billions of market ticks/day
TensorFlow & PyTorch — Python frontend, C++ core for speed optimization
Chrome V8 engine, Firefox — JS engines written in C++
NASA Mars Rovers (Curiosity, Perseverance) — autonomous navigation control
#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;
}
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
print("Step 1: Program starting...")
total_sum = 0
for i in range(1, 100000001):
total_sum += i
print("Step 2: Sum calculated =", total_sum)No Separate Build Step:
Run: python3 main.py
No compilation phase — the interpreter starts immediately.
Line-by-Line Execution:
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)
Choose an IDE · Configure VS Code · Demo OnlineGDB · Analyze "Hello World" code
Lightweight code editor, extensible via Extensions (C/C++ Extension Pack). Cross-platform, integrated Terminal & Git. Recommended for this course.
Professional IDE with powerful code completion, integrated CMake. Free for students (register with @ptit.edu.vn email).
Microsoft's full-featured IDE for Windows. Extremely powerful Debugger, suitable for large projects.
Classic, lightweight IDEs requiring minimal configuration. Commonly used in academic competitions and exams.
Windows: MinGW-w64 (g++) via MSYS2
macOS: xcode-select --install
Linux: sudo apt install build-essential g++
Download VS Code from code.visualstudio.com. Install Extensions: C/C++ (Microsoft) and Code Runner
Open Terminal, type g++ --version. If a version is displayed (e.g., g++ (GCC) 13.2.0) → Installation successful!
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.
cin input in the Console panelAlso worth trying: godbolt.org (Compiler Explorer) lets you inspect the generated Assembly code.

#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
}Preprocessor loads the library to use cout, cin
No need to type std::cout, std::endl
Mandatory function in every C++ program. The OS always calls main() first
The value 0 signals that the program ended normally (no errors)
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
}input[8] occupies exactly 8 contiguous bytes in RAMpassword[8] occupies the NEXT 8 contiguous bytes immediately after inputcin >> input reads until Enter — it does NOT check if input fits in 8 bytespassword!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.
6 chars + null terminator fits within 8 bytes. password is unchanged.

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


cin.width(8); // Read at most 7 chars + null terminator
cin >> input; // Now safe — won't overflowNote: cin.width(n) tells cin to read at most n-1 characters, leaving room for \0
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.
fgets(input, sizeof(input), stdin);
// sizeof(input) = 8 → reads at most 7 chars + \0
// Never writes past the buffer boundaryNote: fgets() always respects the size limit. The classic safe alternative to gets() (which is banned in modern C/C++).
A. Dennis Ritchie
B. Bjarne Stroustrup
C. James Gosling
D. Guido van Rossum
A. Pure Interpreted
B. Compiled, Multi-paradigm
C. Scripting language
D. Mark-up language
A. #include <iostream>
B. using namespace std;
C. int main()
D. return 0;
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.
C++ compiles directly to machine code (Compiled) and supports all 3 programming paradigms: Procedural, OOP, and Generic.
The main() function is the only mandatory Entry Point of every C++ program. The operating system always calls main() first when launching the program.
Program Anatomy · 4-Step Compilation Process · Error Classification · Debugging
Preprocessor · Main Function · Code Blocks · Standard Coding Style

According to the textbook: A C++ program may consist of multiple source files (.cpp, .h), but there can only be ONE single main() function.
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.
Resolves naming conflicts between functions/variables when merging libraries. The using namespace std; directive allows direct use of cout, cin instead of std::cout.
Each statement ends with a semicolon
#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;
}tenSanPham, tongTien)main() function// single-line comment or /* ... */ for multi-line4 Compilation Stages
3 Types of Errors
Debugging Skills
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.
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
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)
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
A. Compiler → Preprocessor → Linker → Assembler
B. Preprocessor → Compiler → Assembler → Linker
C. Linker → Assembler → Compiler → Preprocessor
D. Preprocessor → Assembler → Compiler → Linker
A. Missing closing curly brace {
B. Missing semicolon ;
C. Wrong formula for perimeter (a+b)*3
D. Incorrect library name #include <iostreams>
A. Set Breakpoint B. Run the program immediately
C. Step Over (Execute current line) D. Step Into (Enter inside a function)
Preprocessor handles preprocessing → Compiler translates to Assembly → Assembler translates to Object file → Linker links with libraries to produce .exe.
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.
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.
Variables & Data Types · Type Casting · Operators · Input/Output · Control Structures
Variable Naming Rules
RAM Memory
Type Casting
Operators & Common Pitfalls
DataType variableName = initialValue;
int age = 20; // Integer
double gpa = 8.5; // Floating point
char grade = 'A'; // Character
bool isApproved = true; // BooleanA variable is a named memory cell in RAM used to store data that can change during program execution.
✅ 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).
💡 Use the sizeof(dataType) function to check the actual size: cout << sizeof(int);
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) │
└────────┴───────────────────────── ┘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.
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.
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.5The programmer actively casts the type. Old C style: (double)a. Modern C++ style (recommended): static_cast<double>(a).
+, -, *, / (division), % (modulo — integers only!)
Example: 7 % 3 = 1 (7 divided by 3 gives 2 remainder 1)
x += 5 (equivalent to x = x + 5), -=, *=, /=, %=
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)Return a bool value (true/false):
== (equal), != (not equal)> (greater than), < (less than)>= (greater than or equal to), <= (less than or equal to)&& (AND — True when BOTH are true)|| (OR — True when AT LEAST ONE is true)! (NOT — Reverses the logical value)int tuoi = 20;
bool hasStudentCard = true;
// Student discount condition: age < 22 AND has student card
bool isDiscounted = (tuoi < 22) && hasStudentCard;
// Result: truecout << 5 / 2; // = 2 (NOT 2.5!)
cout << 5.0 / 2; // = 2.5 (5.0 is a double)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!
if (x = 3) { ... } //Standard I/O · Input stream issues with cin.getline · Data formatting with iomanip
Uses the << insertion operator. Combine with endl or '\n' to add a new line.
cout << "Hello " << name
<< ", age: " << age << endl;Uses the >> extraction operator. cin automatically skips whitespace when reading numbers/words.
int age;
cout << "Enter age: ";
cin >> age;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!
#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;
}fixed: Display floating-point numbers in fixed decimal notationsetprecision(n): Set n digits after the decimal pointsetw(w): Set minimum display width to w charactersleft / right: Align text left or right within the setw fieldif-else · switch-case · Ternary Operator · for, while, do-while · break & continue
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";
}Use when comparing a single integer/character variable against fixed values. ⚠️ REQUIRED to have
Syntax: ConditionExpression ? ValueIfTrue : ValueIfFalse;
int maxVal;
if (a > b) {
maxVal = a;
} else {
maxVal = b;
}int maxVal = (a > b) ? a : b;
// Use directly inside cout:
cout << (score >= 5.0 ? "PASSED" : "FAILED");int n;
do {
cout << "Enter n > 0: ";
cin >> n;
} while (n <= 0); // Re-prompt if input is invalidExits the loop COMPLETELY immediately.
for (int i = 1; i <= 10; i++) {
if (i == 5) break;
cout << i << " ";
}
// Output: 1 2 3 4Skips 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 5A. 3.5 and 1 B. 3 and 1 C. 3 and 3.5 D. 3.5 and 0
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
A. for
B. while
C. do-while
D. All of the above loops
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.
cin >> str only reads up to the first whitespace. getline(cin, str) reads the entire line of text including spaces until Enter is pressed.
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.
Number Processing & cmath Library
1D/2D Arrays
Strings
Pointers & Dynamic Allocation
Advanced integer/floating-point types
Common mathematical functions in <cmath>
unsigned int: Stores only non-negative integers (≥ 0), range 0 to 4,294,967,295. Suitable for storing array sizes (size_t).
float: 4 bytes. double: 8 bytes. Constants: 3.14f (float), 3.14 (double). Recommended
Array Data Structure · Traversal & Basic Algorithms · 2D Array Matrices
int a[5] = {10, 20, 30, 40, 50};
// a[0]=10, a[1]=20, a[2]=30, a[3]=40, a[4]=50[ 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)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.
int sum = 0;
for (int i = 0; i < n; i++) {
sum += a[i];
}int maxVal = a[0];
for (int i = 1; i < n; i++) {
if (a[i] > maxVal)
maxVal = a[i];
}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]);
}
}int matrix[2][3] = {
{1, 2, 3}, // Row 0
{4, 5, 6} // Row 1
};for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
cout << matrix[i][j] << " ";
}
cout << endl;
}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 ]C-style strings (char[]) vs C++ string objects (std::string) & String handling methods
#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"); // 0string 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"Memory Address
Operators & and *
Arrays & Pointers
Heap Allocation (new/delete[])
Avoiding Memory Leaks
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!)& (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.
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 = 100A 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.

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)ptr ──► [10][20][30][40][50]
ptr ptr+1 ptr+2 ptr+3 ptr+4In 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.
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 Pointervoid 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!
int* p = new int(42);
delete p; // Free the memory
cout << *p; //A. 3 B. 4 C. 5 D. The address of arr[3]
A. Gets the value of x B. Gets the memory address of x
C. Logical AND operation D. Frees the variable x
A. Do nothing B. Assign arr = nullptr;
C. Call free(arr); afterwards D. Redeclare int arr;
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.
The & operator (Address-of operator) retrieves the RAM memory address of variable x. The * operator is used to dereference and get the value.
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 Knowledge Review · Building the MiniPOS v0.1 Application · Homework Assignment
Chapter 1 — Fundamentals of C++