0% found this document useful (0 votes)
20 views52 pages

CPlusPlus Comprehensive Guide

The document is a comprehensive guide to C++ programming, covering topics from basic syntax to advanced concepts like recursion and object-oriented programming. It includes detailed sections on data types, loops, file processing, and modern C++ features, making it suitable for all skill levels. The guide also emphasizes best practices in coding and compilation techniques.

Uploaded by

entity9993
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views52 pages

CPlusPlus Comprehensive Guide

The document is a comprehensive guide to C++ programming, covering topics from basic syntax to advanced concepts like recursion and object-oriented programming. It includes detailed sections on data types, loops, file processing, and modern C++ features, making it suitable for all skill levels. The guide also emphasizes best practices in coding and compilation techniques.

Uploaded by

entity9993
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

C++

Comprehensive C++
Programming Guide
From First cout to Recursion, OOP & Modern C++

Sections 1-18 . CS Definitions . Code Examples . All Skill Levels

Basics . Data Types . Loops . Scope . Operations . Methods . Input


Conditionals . String Formatting . Random . Algorithm Principles
File I/O . Arrays . Vectors/Maps . OOP . Big 4 . Sorting . Recursion

C++11 / C++14 / C++17 / C++20 . STL . Modern Features


C++ Comprehensive C++ Programming Guide Sections 1-18 . CS Definitions . Examples

Table of Contents
§1 Basics
cout, cin, what is C++, compilation, structure
§2 Data Types & Type Casting
int, double, bool, char, string + casting + auto
§3 Loops
for, while, do-while, range-for, break/continue
§4 Nested Structures & Scope
nesting, block scope, shadowing, namespaces
§5 Operations
arithmetic, <cmath>, string ops, shorthand
§6 Functions & Parameters
functions, pass-by-value/reference, overloading, default args
§7 Input
cin, getline, istringstream, validation
§8 Conditionals
if / else if / else, switch, ternary
§9 String Formatting & Output
cout formatting, iomanip, string operations
§10 Random
<random> header, engines, distributions, seeding
§11 Algorithm Principles
Boolean zen, assert, lookahead, fencepost, DeMorgan
§12 File Processing
ifstream/ofstream, getline, token-based, error handling
§13 Arrays
C-arrays, std::array, value/reference, 2D, pointer basics
§14 Vectors, Maps & More
vector, map, unordered_map, set, STL algorithms
§15 Objects & Classes
fields, constructors, this, const, static, Rule of 3/5
§16 The Big 4
Encapsulation, Inheritance, Polymorphism, Abstraction
§17 Sorting & Searching
std::sort, comparators, binary_search, algorithms, Big O
§18 Recursion
base case, call stack, memoization, classic problems

Page 2
C++ Comprehensive C++ Programming Guide Sections 1-18 . CS Definitions . Examples

§1 Basics
cout · cin · what is C++ · compilation · program structure · headers

What is C++?
C++ is a general-purpose, statically-typed, compiled programming language created by Bjarne
Stroustrup in 1979 as an extension of C. It supports multiple paradigms: procedural, object-oriented,
generic (templates), and functional. C++ compiles directly to native machine code — there is no virtual
machine — giving it maximum performance. It is the language of choice for operating systems, game
engines, embedded systems, high-frequency trading, and performance-critical applications.

Key CS Definitions
Compiled Language
Source (.cpp) is compiled by the compiler (g++/clang++) directly to machine code (.exe or binary).
No bytecode, no runtime interpreter.

Statically Typed
Every variable must have a declared type at compile time. The compiler catches type errors before
running.

Undefined Behavior (UB)


C++ has operations whose behavior the standard does not define — accessing out-of-bounds
memory, using uninitialized variables, signed integer overflow. UB can cause silent data corruption
or crashes.

Header File (.h / .hpp)


Contains declarations (function signatures, class definitions). Included with #include.

Preprocessor
Runs before compilation. Handles #include, #define, #ifdef. Output is pure C++.

Linker
Combines compiled object files (.o) into a final executable. Resolves references between files.

Anatomy of a C++ Program

Page 3
C++ Comprehensive C++ Programming Guide Sections 1-18 . CS Definitions . Examples

// File: [Link]
#include <iostream> // header: gives us cout, cin, endl
#include <string> // header: gives us std::string

// 'using namespace std;' lets us write 'cout' instead of 'std::cout'


using namespace std;

int main() { // entry point — must return int


cout << "Hello, World!" << endl;
return 0; // 0 = success
}
// Compile: g++ -std=c++17 -o hello [Link]
// Run: ./hello

cout and cin


#include <iostream>
using namespace std;

int main() {
// Output with cout (<< is the 'insertion' operator)
cout << "Hello, World!" << endl; // endl flushes buffer
cout << "Hello, World!" << "\n"; // \n is faster (no flush)
cout << 42 << "\n";
cout << 3.14 << "\n";
cout << true << "\n"; // prints 1

// Chaining
cout << "Name: " << "Alice" << ", Age: " << 30 << "\n";

// Input with cin (>> is the 'extraction' operator)


int age;
cout << "Enter your age: ";
cin >> age;
cout << "You are " << age << " years old.\n";

return 0;
}

Comments

Page 4
C++ Comprehensive C++ Programming Guide Sections 1-18 . CS Definitions . Examples

// Single-line comment

/*
* Multi-line comment
*/

/// Doxygen-style documentation comment


/// @param n An integer
/// @return The square of n
int square(int n) { return n * n; }

Compilation Steps
# Single file
g++ -std=c++17 -Wall -o program [Link]

# Multiple files
g++ -std=c++17 -Wall -o program [Link] [Link]

# Common flags:
# -std=c++17 use C++17 standard (also c++11, c++14, c++20)
# -Wall enable all warnings
# -O2 optimization level 2
# -g include debug symbols (for gdb)

■ Always compile with -Wall. Warnings often reveal real bugs. Never ignore undefined behavior — it won't crash
consistently, making it the hardest bug to find.

Page 5
C++ Comprehensive C++ Programming Guide Sections 1-18 . CS Definitions . Examples

§2 Data Types & Type Casting


fundamental types · string · auto · const · casting · size guarantees

Fundamental Types
bool true or false. Size: 1 byte typically.

char 8-bit character. 'A', '\n'. Signed or unsigned (impl. defined).

int Signed integer. Usually 32-bit: ~±2.1B. Most common.

long At least 32-bit. long long guaranteed 64-bit.

float 32-bit IEEE 754 floating-point. Suffix f: 3.14f

double 64-bit IEEE 754 floating-point. Default decimal type: 3.14159

long double Extended precision. At least 64-bit (80- or 128-bit on some


platforms).

unsigned int Non-negative int: 0 to ~4.3B. Never goes negative — wraps around!

size_t Unsigned type for sizes/counts. Use for array indices and .size()
returns.

Page 6
C++ Comprehensive C++ Programming Guide Sections 1-18 . CS Definitions . Examples

#include <iostream>
#include <climits> // INT_MAX etc.
#include <cfloat> // DBL_MAX etc.
using namespace std;

int age = 25;


long long big = 9'000'000'000LL; // ' separator (C++14), LL suffix
double pi = 3.14159265358979;
float tax = 0.075f;
bool isOpen = true;
char grade = 'A';

// auto — compiler deduces type (still statically typed)


auto x = 42; // int
auto name = string("Alice"); // std::string
auto val = 3.14; // double

// Fixed-width types (preferred for portability)


#include <cstdint>
int32_t i32 = -1000;
uint64_t u64 = 18446744073709551615ULL;

// Size inspection
cout << sizeof(int) << "\n"; // 4 (bytes)
cout << sizeof(double) << "\n"; // 8
cout << INT_MAX << "\n"; // 2147483647

std::string
std::string is a class in the C++ standard library. It manages its own memory. Include <string> to use it.
Unlike C-strings (char arrays), it is safe and resizable.

Page 7
C++ Comprehensive C++ Programming Guide Sections 1-18 . CS Definitions . Examples

#include <string>
using namespace std;

string name = "Alice";


string greeting = "Hello, " + name + "!"; // concatenation

cout << [Link]() << "\n"; // 5


cout << [Link]() << "\n"; // 5 (same as length)
cout << name[0] << "\n"; // A
cout << [Link](1) << "\n"; // l (bounds-checked)
cout << [Link](1, 3) << "\n"; // lic (start, count)
cout << [Link]("lic") << "\n"; // 1
cout << [Link]() << "\n"; // 0 (false)
cout << [Link]() << "\n"; // doesn't exist in std!
// Use transform for case conversion:
#include <algorithm>
string upper = name;
transform([Link](), [Link](), [Link](), ::toupper);
cout << upper << "\n"; // ALICE

// Comparison — use == (safe for std::string)


string a = "hello", b = "hello";
cout << (a == b) << "\n"; // 1 (true)

const and constexpr


const double PI = 3.14159265; // runtime constant — cannot be changed
constexpr int MAX = 100; // compile-time constant (C++11)

// const reference — read-only alias, no copy


void print(const string& s) { // safe, efficient
cout << s << "\n";
// s += "x"; ← compile error!
}

Type Casting

Page 8
C++ Comprehensive C++ Programming Guide Sections 1-18 . CS Definitions . Examples

// Implicit widening — safe


int i = 42;
double d = i; // 42.0

// C++ casts (prefer over C-style (type)val)


double pi = 3.99;
int truncated = static_cast<int>(pi); // 3 — truncates
cout << truncated << "\n";

// reinterpret_cast — reinterpret bits (dangerous, low-level)


// const_cast — remove const (use carefully)
// dynamic_cast — safe downcast in class hierarchy (OOP)

// C-style cast (avoid in C++ — no safety checks)


int old_style = (int)pi; // works but discouraged

// String <-> number (C++11)


#include <string>
string s = to_string(42);
int n = stoi("123");
double dv = stod("3.14");

■ Signed integer overflow is undefined behavior in C++. Use long long or unsigned types for large values. Never
assume overflow wraps around — the compiler may optimize it away.

Page 9
C++ Comprehensive C++ Programming Guide Sections 1-18 . CS Definitions . Examples

§3 Loops
for · while · do-while · range-for · break · continue

for Loop
for (int i = 0; i < 5; i++)
cout << i << " "; // 0 1 2 3 4

// Counting down
for (int i = 10; i >= 1; i--)
cout << i << " ";

// Step of 2
for (int i = 0; i <= 20; i += 2)
cout << i << " ";

// Multiple variables
for (int i=0, j=10; i < j; i++, j--)
cout << i << " " << j << "\n";

Range-based for Loop (C++11)


Iterates over every element in any container or array. Clean and safe — no index arithmetic.

#include <vector>
using namespace std;

int arr[] = {2, 3, 5, 7, 11};


for (int n : arr)
cout << n << " "; // 2 3 5 7 11

vector<string> fruits = {"apple", "banana", "cherry"};


for (const string& f : fruits) // const& avoids copying
cout << f << "\n";

// With auto
for (auto& item : fruits)
item += "!"; // modifies in place (& = reference)

while Loop

Page 10
C++ Comprehensive C++ Programming Guide Sections 1-18 . CS Definitions . Examples

int count = 0;
while (count < 5) {
cout << count << "\n";
count++;
}

// Read until sentinel value


int sum = 0, val;
cout << "Enter numbers (0 to stop):\n";
while (cin >> val && val != 0)
sum += val;
cout << "Sum: " << sum << "\n";

do-while Loop
int choice;
do {
cout << "1. Start 2. Help 3. Quit\n";
cout << "Choice: ";
cin >> choice;
} while (choice < 1 || choice > 3);
cout << "You chose: " << choice << "\n";

break and continue


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

// continue
for (int i = 0; i < 10; i++) {
if (i % 2 == 0) continue;
cout << i << " "; // 1 3 5 7 9
}

Page 11
C++ Comprehensive C++ Programming Guide Sections 1-18 . CS Definitions . Examples

§4 Nested Structures & Scope


nested loops · nested if · block scope · namespaces · shadowing

Nested Loops
// Multiplication table
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++)
cout << i*j << "\t";
cout << "\n";
}

// Triangle
for (int row = 1; row <= 5; row++) {
for (int col = 1; col <= row; col++)
cout << "* ";
cout << "\n";
}

Scope in C++
Scope
The region of code where a variable is visible. C++ uses block scope — from declaration to the
closing }. Variables are DESTROYED when their scope ends (RAII).

int global = 100; // global scope

void demo() {
int local = 10; // function scope

if (true) {
int block = 5; // block scope
cout << block << "\n"; // OK
cout << local << "\n"; // OK — outer visible
cout << global << "\n"; // OK — global visible
}
// cout << block; // ERROR — out of scope, also DESTROYED

for (int i = 0; i < 3; i++) { }


// cout << i; // ERROR — i scoped to for loop
}

Page 12
C++ Comprehensive C++ Programming Guide Sections 1-18 . CS Definitions . Examples

Variable Shadowing
int x = 10; // outer x

{
int x = 20; // inner x SHADOWS outer x
cout << x << "\n"; // 20
}
cout << x << "\n"; // 10 — outer x unchanged

// In a class:
class Foo {
int value;
public:
void set(int value) { // parameter shadows field
this->value = value; // this-> disambiguates
}
};

Namespaces
Namespace
A named scope that prevents name collisions between libraries. std:: is the standard library
namespace.

Page 13
C++ Comprehensive C++ Programming Guide Sections 1-18 . CS Definitions . Examples

// Full qualification
std::cout << "Hello\n";
std::string name = "Alice";

// 'using' declaration — bring one name in


using std::cout;
cout << "Hello\n"; // OK without std::

// 'using namespace' — bring entire namespace in


using namespace std;
cout << "Hello\n";
string s = "World";

// Define your own namespace


namespace geometry {
double circleArea(double r) { return 3.14159 * r * r; }
}
double a = geometry::circleArea(5);

// Anonymous namespace — restricts to current file


namespace {
int filePrivate = 42;
}

Page 14
C++ Comprehensive C++ Programming Guide Sections 1-18 . CS Definitions . Examples

§5 Operations
arithmetic · comparison · logical · bitwise · <cmath> · shorthand

Arithmetic Operators
+ Addition: 5 + 3 = 8

- Subtraction: 5 - 3 = 2

* Multiplication: 5 * 3 = 15

/ Division: 7/2=3 (int!), 7.0/2=3.5

% Modulus: 7 % 3 = 1 (integers only)

++ Increment: i++ (post), ++i (pre)

-- Decrement: i-- (post), --i (pre)

cout << 7 / 2 << "\n"; // 3 — integer division!


cout << 7.0 / 2 << "\n"; // 3.5
cout << (double)7/2 << "\n"; // 3.5 — cast first

// Pre vs post increment


int a = 5;
cout << a++ << "\n"; // 5 (use then increment)
cout << a << "\n"; // 6
int b = 5;
cout << ++b << "\n"; // 6 (increment then use)

Comparison & Logical

Page 15
C++ Comprehensive C++ Programming Guide Sections 1-18 . CS Definitions . Examples

cout << (5 == 5) << "\n"; // 1 (true)


cout << (5 != 3) << "\n"; // 1
cout << (5 > 3) << "\n"; // 1
cout << (5 >= 5) << "\n"; // 1

// Logical
cout << (true && false) << "\n"; // 0
cout << (true || false) << "\n"; // 1
cout << (!true) << "\n"; // 0

// Short-circuit
int x = 0;
if (x != 0 && 10/x > 2) // 10/x never evaluated
cout << "yes\n";

Augmented Assignment
int x = 10;
x += 3; x -= 2; x *= 4;
x /= 5; x %= 3;
// No **= in C++; use pow()

string s = "Hello";
s += " World"; // std::string supports +=

The <cmath> Library


#include <cmath>
using namespace std;

cout << M_PI << "\n"; // 3.14159... (non-standard but universal)


cout << acos(-1.0) << "\n"; // PI (portable)
cout << sqrt(144.0) << "\n"; // 12
cout << pow(2, 10) << "\n"; // 1024
cout << abs(-9) << "\n"; // 9 (also fabs for float)
cout << fabs(-9.5) << "\n"; // 9.5
cout << floor(3.9) << "\n"; // 3
cout << ceil(3.1) << "\n"; // 4
cout << round(3.5) << "\n"; // 4
cout << log(exp(1.0)) << "\n"; // 1 (natural log)
cout << log10(1000.0) << "\n"; // 3
cout << sin(acos(-1.0)/2) << "\n"; // 1.0 (sin(PI/2))
cout << hypot(3.0, 4.0) << "\n"; // 5.0

Page 16
C++ Comprehensive C++ Programming Guide Sections 1-18 . CS Definitions . Examples

■ Integer division silently truncates in C++ — it's the number one source of bugs for beginners. Always cast to
double before dividing when you need a decimal result.

Page 17
C++ Comprehensive C++ Programming Guide Sections 1-18 . CS Definitions . Examples

§6 Functions & Parameters


defining functions · pass-by-value vs reference · overloading · default args · inline

Defining Functions
Function
A named reusable block of code. Must be declared before use (or use a prototype).

Return Type
The type returned via return. Use void for no return value.

// returnType functionName(type param, ...) { body }


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

void greet(string name) {


cout << "Hello, " << name << "!\n";
}

int main() {
cout << add(3, 5) << "\n"; // 8
greet("Alice"); // Hello, Alice!
return 0;
}

Pass-by-Value vs Pass-by-Reference
Pass-by-Value
A copy is made. The original is unaffected.

Pass-by-Reference (&)
An alias to the original. Changes affect the caller. No copy — efficient for large objects.

Pass-by-const-Reference
Read-only alias — efficient AND safe. Use for large objects you don't need to modify.

Page 18
C++ Comprehensive C++ Programming Guide Sections 1-18 . CS Definitions . Examples

// By value — copy
void doubleVal(int x) { x *= 2; } // original unchanged

// By reference — modifies original


void doubleRef(int& x) { x *= 2; }

// By const reference — efficient read-only


void printStr(const string& s) { cout << s << "\n"; }

int n = 5;
doubleVal(n); cout << n << "\n"; // 5 — unchanged
doubleRef(n); cout << n << "\n"; // 10 — changed!

// Returning multiple values via references


void minMax(const vector<int>& v, int& mn, int& mx) {
mn = *min_element([Link](), [Link]());
mx = *max_element([Link](), [Link]());
}
int lo, hi;
minMax({3,1,9,5}, lo, hi);
cout << lo << " " << hi << "\n"; // 1 9

Default Arguments
void describePet(string name, string animal="dog", int age=1) {
cout << name << " is a " << age << "-yr-old " << animal << "\n";
}

describePet("Buddy"); // uses defaults


describePet("Whiskers", "cat", 3); // all specified
// Note: default args must be at the END

Function Overloading
double area(double r) { return 3.14159 * r * r; } // circle
double area(double w, double h) { return w * h; } // rectangle

cout << area(5.0) << "\n"; // circle


cout << area(4.0, 6) << "\n"; // rectangle

Function Prototypes

Page 19
C++ Comprehensive C++ Programming Guide Sections 1-18 . CS Definitions . Examples

// Declare before main, define after — needed for mutual calls


double toFahrenheit(double c); // prototype (declaration)

int main() {
cout << toFahrenheit(100) << "\n"; // 212
return 0;
}

double toFahrenheit(double c) { // definition


return c * 9.0/5.0 + 32;
}

Inline Functions & Lambda (C++11)


// inline — compiler may inline the call (hint, not command)
inline int square(int x) { return x*x; }

// Lambda — anonymous function


auto square2 = [](int x) { return x*x; };
cout << square2(5) << "\n"; // 25

// Lambda with capture


int factor = 3;
auto multiply = [factor](int x) { return x * factor; };
cout << multiply(7) << "\n"; // 21

// Used with STL algorithms


vector<int> nums{5,2,8,1,9};
sort([Link](), [Link](), [](int a, int b){ return a > b; });
// descending: 9 8 5 2 1

Page 20
C++ Comprehensive C++ Programming Guide Sections 1-18 . CS Definitions . Examples

§7 Input
cin · getline · istringstream · input validation · [Link]()

cin — Token-Based Input


cin >> reads one whitespace-delimited token. It leaves the newline in the buffer.

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

int main() {
string name;
cout << "Enter your name: ";
cin >> name; // reads one word — stops at space
cout << "Hello, " << name << "!\n";

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

double gpa;
cin >> gpa; // reads double
return 0;
}

getline — Full Line Input


getline reads an entire line including spaces. After using cin >>, call [Link]() to discard the leftover
newline.

string fullName;
int age;

cin >> age;


[Link](); // discard leftover '\n' from cin >>
getline(cin, fullName); // now reads the full line correctly

// Or use [Link](numeric_limits<streamsize>::max(), '\n')


// for robustness

Multiple Values on One Line

Page 21
C++ Comprehensive C++ Programming Guide Sections 1-18 . CS Definitions . Examples

// Input: "10 20 30"


int a, b, c;
cin >> a >> b >> c; // chain extractions
cout << a+b+c << "\n";

// Using istringstream to parse a line


#include <sstream>
string line;
getline(cin, line); // "3 14 159"
istringstream iss(line);
int x, y, z;
iss >> x >> y >> z;
cout << x << " " << y << " " << z << "\n";

Input Validation
int age = -1;
while (age < 0 || age > 120) {
cout << "Enter age (0-120): ";
if (!(cin >> age)) { // extraction failed (non-numeric)
[Link](); // clear error flags
[Link](1000, '\n'); // discard bad input
age = -1;
} else if (age < 0 || age > 120) {
cout << "Out of range.\n";
}
}
cout << "Valid age: " << age << "\n";

■ After a failed cin >> extraction, the stream enters an error state. You MUST call [Link]() before any further
reads will work.

Page 22
C++ Comprehensive C++ Programming Guide Sections 1-18 . CS Definitions . Examples

§8 Conditionals
if / else if / else · switch · ternary · if-initializer (C++17)

if / else if / else
int score = 85;
string grade;

if (score >= 90) grade = "A";


else if (score >= 80) grade = "B";
else if (score >= 70) grade = "C";
else if (score >= 60) grade = "D";
else grade = "F";

cout << "Grade: " << grade << "\n"; // Grade: B

Ternary Operator
int age = 20;
string status = (age >= 18) ? "adult" : "minor";
cout << status << "\n"; // adult

// Compact abs
int x = -7;
int absX = (x >= 0) ? x : -x;

switch Statement

Page 23
C++ Comprehensive C++ Programming Guide Sections 1-18 . CS Definitions . Examples

int day = 3;
switch (day) {
case 1: cout << "Monday"; break;
case 2: cout << "Tuesday"; break;
case 3: cout << "Wednesday"; break;
case 4:
case 5: cout << "Thu or Fri"; break; // fall-through
default: cout << "Weekend";
}

// Switch on char
char grade = 'B';
switch (grade) {
case 'A': cout << "Excellent"; break;
case 'B': cout << "Good"; break;
case 'C': cout << "Average"; break;
default: cout << "Below average";
}

if with Initializer (C++17)


C++17 allows an initializer statement inside if/switch — the variable is scoped to the block.

// if (initializer; condition)
if (int val = compute(); val > 0) {
cout << "Positive: " << val << "\n";
} else {
cout << "Non-positive: " << val << "\n";
}
// val is not accessible here

// Practical: file open check


#include <fstream>
if (ifstream f("[Link]"); f.is_open()) {
// process file
} else {
cerr << "File not found\n";
}

■ Always include break in each switch case unless fall-through is intentional. Annotate intentional fall-through
with a comment: // [[fallthrough]]

Page 24
C++ Comprehensive C++ Programming Guide Sections 1-18 . CS Definitions . Examples

§9 String Formatting & Output


cout with iomanip · printf · string operations · std::format (C++20)

<iomanip> Formatting
The <iomanip> header provides manipulators to control cout output format. Most manipulators are
'sticky' — they persist until changed.

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

double pi = 3.14159265;

// Floating point precision


cout << fixed << setprecision(2) << pi << "\n"; // 3.14
cout << fixed << setprecision(5) << pi << "\n"; // 3.14159
cout << scientific << pi << "\n"; // 3.141593e+00
cout << defaultfloat; // reset to default

// Width and alignment


cout << setw(10) << 42 << "\n"; // 42 (right)
cout << left << setw(10) << 42 << "\n"; // 42 (left)
cout << right << setw(10) << 42 << "\n"; // 42
cout << setfill('0') << setw(8) << 42 << "\n"; // 00000042

// Integers in different bases


cout << hex << 255 << "\n"; // ff
cout << oct << 255 << "\n"; // 377
cout << dec << 255 << "\n"; // 255 (reset)
cout << uppercase << hex << 255 << "\n"; // FF

// Boolean
cout << boolalpha << true << "\n"; // true (not 1)
cout << noboolalpha; // reset

printf (C-style)

Page 25
C++ Comprehensive C++ Programming Guide Sections 1-18 . CS Definitions . Examples

#include <cstdio>

printf("Hello, %s! You are %d years old.\n", "Alice", 25);


printf("Pi = %.4f\n", 3.14159); // Pi = 3.1416
printf("%10.2f\n", 3.14); // 3.14 (width 10)
printf("%-10s|%d\n", "Alice", 95); // Alice |95
printf("%08d\n", 42); // 00000042
printf("%e\n", 12345.6789); // 1.234568e+04

std::format (C++20)
#include <format> // C++20 only
using namespace std;

string s = format("Hello, {}!", "Alice");


string n = format("{:.2f}", 3.14159); // "3.14"
string t = format("{:>10}", "hi"); // " hi"
string u = format("{:0>8d}", 42); // "00000042"
cout << format("{:<10} {:>5}\n", "Name", "Score");
cout << format("{:<10} {:>5}\n", "Alice", 95);

String Operations
#include <string>
#include <sstream>
using namespace std;

// Number to string
string s1 = to_string(42);
string s2 = to_string(3.14);

// String to number
int n = stoi("123");
double d = stod("3.14");
long l = stol("123456789");

// ostringstream — build strings like cout


ostringstream oss;
oss << "Name: " << "Alice" << ", Score: " << fixed
<< setprecision(1) << 95.5;
string result = [Link]();
cout << result << "\n";

Page 26
C++ Comprehensive C++ Programming Guide Sections 1-18 . CS Definitions . Examples

§10 Random
<random> header · engines · distributions · seeding · legacy rand()

Modern C++ Random (<random>, C++11)


C++11 introduced a powerful random number framework separating the engine (source of randomness)
from the distribution (range/shape).

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

// 1. Create an engine
mt19937 rng(42); // Mersenne Twister, seed=42

// 2. Create a distribution
uniform_int_distribution<int> die(1, 6); // [1, 6]
uniform_real_distribution<double> prob(0, 1); // [0.0, 1.0)
normal_distribution<double> gauss(170, 10); // mean=170, sd=10

// 3. Generate numbers
for (int i = 0; i < 5; i++)
cout << die(rng) << " ";
cout << "\n";

cout << prob(rng) << "\n"; // e.g. 0.7324


cout << gauss(rng) << "\n"; // e.g. 165.3

Non-Deterministic Seed
// random_device gives a truly random seed from the OS
random_device rd;
mt19937 rng(rd()); // different every run

uniform_int_distribution<int> die(1, 6);


cout << die(rng) << "\n"; // unpredictable

Shuffling

Page 27
C++ Comprehensive C++ Programming Guide Sections 1-18 . CS Definitions . Examples

#include <algorithm>
#include <vector>
using namespace std;

vector<int> deck(52);
iota([Link](), [Link](), 1); // fill 1..52

mt19937 rng(random_device{}());
shuffle([Link](), [Link](), rng);

for (int i=0; i<5; i++) cout << deck[i] << " ";

Legacy rand() — Avoid in New Code


#include <cstdlib>
#include <ctime>

srand(time(nullptr)); // seed with current time

int roll = rand() % 6 + 1; // die: 1-6 (biased!)


double r = (double)rand() / RAND_MAX; // [0, 1]

// rand() has poor statistical properties and is NOT thread-safe


// Use <random> for any serious work

■ rand() % N is biased when RAND_MAX+1 is not divisible by N. Always prefer std::uniform_int_distribution for
correct results.

Page 28
C++ Comprehensive C++ Programming Guide Sections 1-18 . CS Definitions . Examples

§11 Algorithm Principles


Boolean zen · assert · lookahead · fencepost · DeMorgan's Law

Boolean Zen
bool isValid = true;

// BAD
if (isValid == true) { /* ... */ }
if (found == false) { /* ... */ }

// GOOD
if (isValid) { /* ... */ }
if (!found) { /* ... */ }

// BAD
bool isEven(int n) {
if (n % 2 == 0) return true;
else return false;
}
// GOOD
bool isEven(int n) { return n % 2 == 0; }

assert
#include <cassert>

double divide(double a, double b) {


assert(b != 0 && "Denominator must not be zero");
return a / b;
}
// Assertions are disabled in release builds with: -DNDEBUG
// Use static_assert for compile-time checks:
static_assert(sizeof(int) == 4, "Expected 32-bit int");

Fencepost Problem

Page 29
C++ Comprehensive C++ Programming Guide Sections 1-18 . CS Definitions . Examples

vector<string> fruits = {"apple", "banana", "cherry"};

// WRONG — trailing separator


for (const auto& f : fruits)
cout << f << ", "; // apple, banana, cherry, ← extra!

// CORRECT — separator before all but first


for (size_t i = 0; i < [Link](); i++) {
if (i > 0) cout << ", ";
cout << fruits[i];
}
cout << "\n"; // apple, banana, cherry

// CORRECT — with ostringstream join


// (no std::join in C++, but easy to write)

Lookahead
vector<int> nums = {1, 2, 2, 3, 4, 4, 4, 5};

for (size_t i = 0; i+1 < [Link](); i++)


if (nums[i] == nums[i+1])
cout << "Dup at " << i << ": " << nums[i] << "\n";

DeMorgan's Laws
!(A && B) = !A || !B

!(A || B) = !A && !B

int x = 3, y = 8;

if (!(x > 5 && y < 10)) cout << "DeMorgan 1\n"; // original
if (x <= 5 || y >= 10) cout << "DeMorgan 1\n"; // equivalent

bool done=false, error=false;


while (!done && !error) { // DeMorgan of !(done||error)
// process
}

Page 30
C++ Comprehensive C++ Programming Guide Sections 1-18 . CS Definitions . Examples

§12 File Processing


ifstream · ofstream · getline · token-based · error handling · filesystem

Reading with ifstream


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

int main() {
ifstream inFile("[Link]");
if (!inFile) { // check if open succeeded
cerr << "Cannot open file\n";
return 1;
}

// Line-by-line
string line;
while (getline(inFile, line))
cout << line << "\n";

[Link]();
return 0;
}

Writing with ofstream


ofstream outFile("[Link]"); // creates or overwrites
if (!outFile) { cerr << "Error opening file\n"; return 1; }

outFile << "Hello, File!\n";


outFile << "Second line\n";
[Link]();

// Append mode
ofstream logFile("[Link]", ios::app);
logFile << "New entry\n";

Token-Based Reading

Page 31
C++ Comprehensive C++ Programming Guide Sections 1-18 . CS Definitions . Examples

// File: "Alice 95\nBob 82\nCarol 91"


ifstream f("[Link]");
string name;
int score;
while (f >> name >> score)
cout << left << setw(10) << name << score << "\n";

RAII with Scoped ifstream


// ifstream closes automatically when it goes out of scope (RAII)
{
ifstream f("[Link]");
if (f) {
string line;
while (getline(f, line))
process(line);
}
} // [Link]() called automatically here

Reading All Lines into a Vector


#include <fstream>
#include <vector>
#include <string>
using namespace std;

vector<string> readLines(const string& filename) {


vector<string> lines;
ifstream f(filename);
string line;
while (getline(f, line))
lines.push_back(line);
return lines;
}

std::filesystem (C++17)

Page 32
C++ Comprehensive C++ Programming Guide Sections 1-18 . CS Definitions . Examples

#include <filesystem>
namespace fs = std::filesystem;

if (fs::exists("[Link]"))
cout << "File size: " << fs::file_size("[Link]") << "\n";

// Iterate directory
for (const auto& entry : fs::directory_iterator("."))
cout << [Link]() << "\n";

Page 33
C++ Comprehensive C++ Programming Guide Sections 1-18 . CS Definitions . Examples

§13 Arrays
C-arrays · std::array · pointer basics · value/reference · 2D arrays

C-Style Arrays
Array
A fixed-size contiguous block of same-type elements. No bounds checking. Decays to a pointer
when passed to functions.

int primes[5] = {2, 3, 5, 7, 11}; // fixed size


int zeros[10]; // uninitialized! (UB to read)
int filled[10] = {}; // zero-initialized

cout << primes[0] << "\n"; // 2


cout << primes[4] << "\n"; // 11
primes[2] = 99;

// sizeof gives TOTAL bytes — divide for count


int count = sizeof(primes) / sizeof(primes[0]); // 5

// Danger: no bounds checking


// primes[10] = 42; // undefined behavior! silent corruption

std::array (C++11) — Preferred


std::array is a fixed-size array wrapper that knows its own size, supports iterators, and doesn't decay to a
pointer.

Page 34
C++ Comprehensive C++ Programming Guide Sections 1-18 . CS Definitions . Examples

#include <array>
using namespace std;

array<int, 5> primes = {2, 3, 5, 7, 11};

cout << [Link]() << "\n"; // 5


cout << primes[0] << "\n"; // 2
cout << [Link](10) << "\n"; // throws std::out_of_range!
cout << [Link]() << "\n"; // 2
cout << [Link]() << "\n"; // 11

// Range-for works
for (int n : primes)
cout << n << " ";

// Sort, find
sort([Link](), [Link]());
auto it = find([Link](), [Link](), 5);

Value vs Reference Semantics


// Arrays DO NOT copy when assigned (they decay to pointers)
int a[] = {1, 2, 3};
int* p = a; // p points into a
p[0] = 99;
cout << a[0] << "\n"; // 99 — a is affected!

// std::array DOES copy on assignment


array<int,3> x = {1,2,3};
array<int,3> y = x; // true copy
y[0] = 99;
cout << x[0] << "\n"; // 1 — unchanged

2D Arrays

Page 35
C++ Comprehensive C++ Programming Guide Sections 1-18 . CS Definitions . Examples

int grid[3][3] = {{1,2,3},{4,5,6},{7,8,9}};

cout << grid[1][2] << "\n"; // 6

for (int r=0; r<3; r++) {


for (int c=0; c<3; c++)
cout << setw(4) << grid[r][c];
cout << "\n";
}

// Passing to a function — must specify all but first dimension


void print(int m[][3], int rows) {
for (int r=0; r<rows; r++) {
for (int c=0; c<3; c++) cout << m[r][c] << " ";
cout << "\n";
}
}

■ Prefer std::vector over C-arrays for dynamic or function-passed data, and std::array over C-arrays for
fixed-size data. Both are safer and more idiomatic.

Page 36
C++ Comprehensive C++ Programming Guide Sections 1-18 . CS Definitions . Examples

§14 Vectors, Maps & More


vector · map · unordered_map · set · STL algorithms · iterators

std::vector — Dynamic Array


#include <vector>
using namespace std;

vector<string> names;
names.push_back("Alice");
names.push_back("Bob");
names.push_back("Carol");
[Link]([Link]()+1, "Dave"); // insert at index 1

cout << names[0] << "\n"; // Alice


cout << [Link](2) << "\n"; // Carol (bounds-checked)
cout << [Link]() << "\n"; // 4
cout << [Link]() << "\n"; // Alice
cout << [Link]() << "\n"; // Dave? (after insert)

names.pop_back(); // remove last


[Link]([Link]() + 1); // remove at index

// Initializer list
vector<int> nums = {5, 2, 8, 1, 9, 3};

// Reserve space to avoid reallocations


vector<int> big;
[Link](10000);

// 2D vector
vector<vector<int>> matrix(3, vector<int>(4, 0));
matrix[1][2] = 7;

std::map — Sorted Key-Value Store

Page 37
C++ Comprehensive C++ Programming Guide Sections 1-18 . CS Definitions . Examples

#include <map>
using namespace std;

map<string, int> scores;


scores["Alice"] = 95;
scores["Bob"] = 82;
scores["Carol"] = 91;
scores["Alice"] = 98; // overwrites

cout << scores["Alice"] << "\n"; // 98


// scores["Dave"] inserts 0! Use count() or find() first:
if ([Link]("Dave"))
cout << scores["Dave"] << "\n";

// Safe access with find


auto it = [Link]("Bob");
if (it != [Link]())
cout << it->first << ": " << it->second << "\n";

// Iterate (sorted by key)


for (const auto& [name, score] : scores) // C++17 structured binding
cout << name << ": " << score << "\n";

[Link]("Bob");
cout << [Link]() << "\n"; // 2

std::unordered_map — Hash Map O(1)


#include <unordered_map>
using namespace std;

unordered_map<string, int> freq;


for (const string& w : {"the","cat","sat","the","cat","the"})
freq[w]++;

for (const auto& [word, count] : freq)


cout << word << ": " << count << "\n";

std::set & std::unordered_set

Page 38
C++ Comprehensive C++ Programming Guide Sections 1-18 . CS Definitions . Examples

#include <set>
#include <unordered_set>
using namespace std;

set<int> s = {4,2,7,1,4,2}; // sorted, unique: {1,2,4,7}


[Link](5);
[Link](2);
cout << [Link](4) << "\n"; // 1 (present)

// Remove duplicates from vector


vector<int> v = {1,2,2,3,3,3};
unordered_set<int> unique([Link](), [Link]());

STL Algorithms (<algorithm>)


#include <algorithm>
#include <numeric>
using namespace std;

vector<int> v = {5,2,8,1,9,3};

sort([Link](), [Link]()); // ascending


sort([Link](), [Link](), greater<int>()); // descending

auto it = find([Link](), [Link](), 8);


bool has = (it != [Link]());

int total = accumulate([Link](), [Link](), 0);


int mx = *max_element([Link](), [Link]());
int mn = *min_element([Link](), [Link]());

// count_if, any_of, all_of, none_of


int evens = count_if([Link](), [Link](), [](int x){ return x%2==0; });
bool allPos = all_of([Link](), [Link](), [](int x){ return x>0; });

// transform — map values


vector<int> sq([Link]());
transform([Link](), [Link](), [Link](), [](int x){ return x*x; });

Page 39
C++ Comprehensive C++ Programming Guide Sections 1-18 . CS Definitions . Examples

§15 Objects & Classes


fields · constructors · this · const · static · Rule of 3/5 · operator overloading

OOP Core Terms


Class
Blueprint defining member variables (fields) and member functions (methods).

Object
An instance created with the class type (or new for heap allocation).

Member
A field or method belonging to a class.

Access Modifiers
public (accessible anywhere), private (class only), protected (class + subclasses). Default in class:
private; in struct: public.

Page 40
C++ Comprehensive C++ Programming Guide Sections 1-18 . CS Definitions . Examples

class Dog {
public:
// Constructor
Dog(string name, int age, string breed)
: name(name), age(age), breed(breed) { // member initializer list
totalDogs++;
}

// Destructor — called when object is destroyed


~Dog() { totalDogs--; }

// Const method — does not modify the object


string bark() const { return name + " says: Woof!"; }
string getName() const { return name; }
int getAge() const { return age; }
void birthday() { age++; }

// Static method
static int getTotalDogs() { return totalDogs; }

// Operator overloading
bool operator<(const Dog& other) const { return age < [Link]; }

// Friend for << operator


friend ostream& operator<<(ostream& os, const Dog& d) {
return os << "Dog(" << [Link] << ", " << [Link] << "yo, " << [Link] << ")";
}

private:
string name;
int age;
string breed;
static int totalDogs; // declaration
};

int Dog::totalDogs = 0; // definition (outside class)

// Usage
Dog d1("Rex", 3, "German Shepherd");
Dog d2("Fluffy", 1, "Poodle");
cout << [Link]() << "\n"; // Rex says: Woof!
cout << d1 << "\n"; // Dog(Rex, 3yo, German Shepherd)
cout << Dog::getTotalDogs() << "\n"; // 2
cout << (d2 < d1) << "\n"; // 1 (true — d2 younger)

Constructors & Initializer Lists

Page 41
C++ Comprehensive C++ Programming Guide Sections 1-18 . CS Definitions . Examples

class Point {
public:
double x, y;

Point() : x(0), y(0) {} // default constructor


Point(double x, double y) : x(x), y(y) {}
Point(const Point& other) : x(other.x), y(other.y) {} // copy

double distanceTo(const Point& other) const {


double dx = x - other.x, dy = y - other.y;
return sqrt(dx*dx + dy*dy);
}
};

Rule of 3 / 5 / 0
If a class manages a resource (heap memory, file handle), define all of: destructor, copy constructor,
copy assignment. With C++11 move semantics: also move constructor and move assignment (Rule of
5). Or use RAII containers and define none (Rule of 0).

Page 42
C++ Comprehensive C++ Programming Guide Sections 1-18 . CS Definitions . Examples

§16 The Big 4


Encapsulation · Inheritance · Polymorphism · Abstraction

1. Encapsulation
Encapsulation
Bundling data and methods together, hiding internal state behind an interface using
private/protected. Protects class invariants.

class BankAccount {
string owner;
double balance; // private by default in class

public:
BankAccount(string o, double b=0)
: owner(o), balance(max(0.0, b)) {}

double getBalance() const { return balance; }


string getOwner() const { return owner; }

void deposit(double amount) {


if (amount > 0) balance += amount;
}
bool withdraw(double amount) {
if (amount > 0 && amount <= balance)
{ balance -= amount; return true; }
return false;
}
friend ostream& operator<<(ostream& os, const BankAccount& a) {
return os << [Link] << ": $" << fixed
<< setprecision(2) << [Link];
}
};

2. Inheritance
Inheritance
A derived class (child) inherits from a base class (parent) using the : syntax. C++ supports multiple
inheritance (inheriting from more than one base).

Page 43
C++ Comprehensive C++ Programming Guide Sections 1-18 . CS Definitions . Examples

class Animal {
protected:
string name;
int age;
public:
Animal(string n, int a) : name(n), age(a) {}
virtual string speak() const { return "..."; } // virtual!
void eat() const { cout << name << " is eating.\n"; }
virtual ~Animal() {} // virtual destructor — essential!
};

class Dog : public Animal {


string breed;
public:
Dog(string n, int a, string b) : Animal(n,a), breed(b) {}
string speak() const override { return "Woof!"; } // override
string fetch() const { return name+" fetches!"; }
};

class Cat : public Animal {


public:
Cat(string n, int a) : Animal(n,a) {}
string speak() const override { return "Meow!"; }
};

Dog d("Rex",3,"Lab");
cout << [Link]() << "\n"; // Woof!
[Link](); // Rex is eating. (inherited)
cout << (d is Animal?) << "\n"; // use dynamic_cast or typeid

3. Polymorphism
Polymorphism
Virtual functions enable runtime polymorphism — the correct function is chosen based on the actual
object type, even through a base-class pointer/reference. Requires the virtual keyword in the base
class.

Page 44
C++ Comprehensive C++ Programming Guide Sections 1-18 . CS Definitions . Examples

// Polymorphic array of Animals


vector<Animal*> zoo = {
new Dog("Rex",3,"Lab"),
new Cat("Luna",2),
new Dog("Buddy",1,"Poodle")
};

for (Animal* a : zoo)


cout << a->speak() << "\n"; // Woof! Meow! Woof!
// calls the CORRECT version at runtime

// Clean up (virtual destructor ensures correct destructor called)


for (Animal* a : zoo) delete a;

// Modern C++: use smart pointers instead!


#include <memory>
vector<unique_ptr<Animal>> zoo2;
zoo2.push_back(make_unique<Dog>("Rex",3,"Lab"));
zoo2.push_back(make_unique<Cat>("Luna",2));
for (const auto& a : zoo2) cout << a->speak() << "\n";

4. Abstraction
Abstraction
Hiding implementation details. C++ achieves this with pure virtual functions (= 0) making a class
abstract — it cannot be instantiated directly.

Page 45
C++ Comprehensive C++ Programming Guide Sections 1-18 . CS Definitions . Examples

class Shape {
public:
virtual double area() const = 0; // pure virtual
virtual double perimeter() const = 0;
virtual void describe() const { // concrete
cout << typeid(*this).name()
<< " area=" << fixed << setprecision(2) << area() << "\n";
}
virtual ~Shape() {}
};
// Shape s; ← compile error: abstract class!

class Circle : public Shape {


double r;
public:
Circle(double r) : r(r) {}
double area() const override { return acos(-1.0)*r*r; }
double perimeter() const override { return 2*acos(-1.0)*r; }
};

class Rectangle : public Shape {


double w, h;
public:
Rectangle(double w, double h) : w(w), h(h) {}
double area() const override { return w*h; }
double perimeter() const override { return 2*(w+h); }
};

vector<unique_ptr<Shape>> shapes;
shapes.push_back(make_unique<Circle>(5));
shapes.push_back(make_unique<Rectangle>(4,6));
for (const auto& s : shapes) s->describe();

Page 46
C++ Comprehensive C++ Programming Guide Sections 1-18 . CS Definitions . Examples

§17 Sorting & Searching


std::sort · comparators · std::binary_search · algorithms · Big O

Big O Complexity
O(1) Constant: array index, unordered_map lookup

O(log n) Logarithmic: binary search, map/set operations

O(n) Linear: linear search, single loop through container

O(n log n) Linearithmic: std::sort (introsort), stable_sort

O(n²) Quadratic: bubble/insertion sort worst case, nested loops

O(2■) Exponential: naive recursion, power sets

std::sort — Built-in O(n log n)


#include <algorithm>
#include <vector>
using namespace std;

vector<int> v = {5,2,8,1,9,3};
sort([Link](), [Link]()); // ascending
sort([Link](), [Link](), greater<int>()); // descending

// Custom comparator — sort strings by length


vector<string> words = {"banana","apple","fig","cherry"};
sort([Link](), [Link](),
[](const string& a, const string& b){ return [Link]()<[Link](); });

// Sort array
int arr[] = {5,2,8,1,9};
sort(arr, arr+5);

// stable_sort — preserves relative order of equal elements


stable_sort([Link](), [Link]());

// Sort structs
struct Student { string name; int score; };
vector<Student> sts = {{"Alice",95},{"Bob",82},{"Carol",91}};
sort([Link](), [Link](),
[](const Student& a, const Student& b){ return [Link] > [Link]; });

Page 47
C++ Comprehensive C++ Programming Guide Sections 1-18 . CS Definitions . Examples

Linear Search — O(n)


// Manual
int linearSearch(const vector<int>& v, int target) {
for (int i=0; i<(int)[Link](); i++)
if (v[i]==target) return i;
return -1;
}

// STL
auto it = find([Link](), [Link](), 8);
if (it != [Link]())
cout << "Found at index " << (it - [Link]()) << "\n";

Binary Search — O(log n)


// Requires SORTED container
sort([Link](), [Link]());

// STL (returns bool)


bool found = binary_search([Link](), [Link](), 5);

// lower_bound / upper_bound — return iterators


auto lo = lower_bound([Link](), [Link](), 5); // first >= 5
auto hi = upper_bound([Link](), [Link](), 5); // first > 5

// Manual implementation
int bsearch(const vector<int>& v, int target) {
int lo=0, hi=(int)[Link]()-1;
while (lo <= hi) {
int mid = lo + (hi-lo)/2;
if (v[mid]==target) return mid;
else if (v[mid] < target) lo = mid+1;
else hi = mid-1;
}
return -1;
}

Merge Sort — O(n log n)

Page 48
C++ Comprehensive C++ Programming Guide Sections 1-18 . CS Definitions . Examples

void mergeSort(vector<int>& v, int l, int r) {


if (l >= r) return;
int m = l + (r-l)/2;
mergeSort(v, l, m);
mergeSort(v, m+1, r);
inplace_merge([Link]()+l, [Link]()+m+1, [Link]()+r+1);
}
// Call: mergeSort(v, 0, [Link]()-1);

Page 49
C++ Comprehensive C++ Programming Guide Sections 1-18 . CS Definitions . Examples

§18 Recursion
base case · call stack · memoization · classic problems · tail recursion

What is Recursion?
A function calls itself to solve a smaller version of the same problem. Every recursive solution needs:

• Base case — the simplest input solved directly without recursion.


• Recursive case — reduce the problem and call self.
• Progress — each call must move CLOSER to the base case.
Call Stack
Each call pushes a stack frame. Recursive calls accumulate frames until the base case, then
unwind. C++ stack is typically 1–8 MB — deep recursion causes a stack overflow (segmentation
fault or stack smashing, no friendly error message).

Factorial
long long factorial(int n) {
if (n == 0) return 1; // base case
return n * factorial(n - 1); // recursive case
}
cout << factorial(5) << "\n"; // 120
cout << factorial(0) << "\n"; // 1

Fibonacci with Memoization

Page 50
C++ Comprehensive C++ Programming Guide Sections 1-18 . CS Definitions . Examples

// Naive O(2^n)
int fib(int n) {
if (n <= 1) return n;
return fib(n-1) + fib(n-2);
}

// Memoized O(n) — use unordered_map as cache


#include <unordered_map>
unordered_map<int,long long> memo;

long long fibMemo(int n) {


if (n <= 1) return n;
auto it = [Link](n);
if (it != [Link]()) return it->second;
return memo[n] = fibMemo(n-1) + fibMemo(n-2);
}

for (int i=0; i<10; i++) cout << fibMemo(i) << " ";
// 0 1 1 2 3 5 8 13 21 34

Array Sum
int sum(const vector<int>& v, int i) {
if (i == (int)[Link]()) return 0;
return v[i] + sum(v, i+1);
}
// Call: sum({1,2,3,4,5}, 0) == 15

Power — Divide & Conquer O(log n)


double fastPow(double base, int exp) {
if (exp == 0) return 1;
if (exp % 2 == 0) {
double half = fastPow(base, exp/2);
return half * half;
}
return base * fastPow(base, exp-1);
}
cout << fastPow(2, 10) << "\n"; // 1024

Tower of Hanoi

Page 51
C++ Comprehensive C++ Programming Guide Sections 1-18 . CS Definitions . Examples

void hanoi(int n, char src, char dst, char aux) {


if (n == 1) {
cout << "Move disk 1: " << src << " -> " << dst << "\n";
return;
}
hanoi(n-1, src, aux, dst);
cout << "Move disk " << n << ": " << src << " -> " << dst << "\n";
hanoi(n-1, aux, dst, src);
}
hanoi(3, 'A', 'C', 'B'); // 2^3 - 1 = 7 moves

Recursion vs Iteration — Summary


Readability Recursion mirrors mathematical definitions. Iteration is more explicit.

Performance Iteration is faster (no frame overhead). C++ stack is limited.

Stack safety Deep C++ recursion causes segfault with no nice error. Use iteration
for depth > ~10k.

Best uses Trees, graphs, divide & conquer, backtracking, parsing.

Memoization unordered_map cache converts exponential recursion to linear.

Tail recursion Some compilers optimise tail-recursive functions to loops (-O2).

End of Guide
You have covered all 18 sections of the Comprehensive C++ Programming Guide.
Happy coding! C++

Page 52

You might also like