๐Ÿš€ C++ Fundamentals - Complete Notes ๐Ÿ“š

Welcome! This guide will take you from zero to hero in C++ programming. Each concept is explained with examples, visuals, and practical tips.


๐Ÿ“‘ Table of Contents

  1. What is C++?
  2. Literals
  3. Comments
  4. Variables
  5. Data Types
  6. Print Output
  7. Operators Part 1
  8. Operators Part 2
  9. Booleans
  10. If-Else
  11. Else-If Ladder
  12. While Loop
  13. For Loop
  14. Loops Standard Problems
  15. Break and Continue
  16. Switch Statement
  17. Functions
  18. Function Arguments
  19. Return Statement
  20. Local Variable
  21. Why Do We Use Arguments and Return Type?
  22. Standard Library Functions
  23. Nested Functions
  24. Arrays
  25. Iterating and Updating Arrays
  26. Taking Input in Arrays
  27. Arrays Memory Allocation
  28. Caveats in C++ Arrays
  29. Quiz: Arrays Theory
  30. Ranged For Loops
  31. Arrays and Functions
  32. Passing Array in Functions
  33. Strings
  34. Taking Input in Strings
  35. String vs Arrays
  36. Basic Functions of String
  37. Vector Basics
  38. Vector Implementation - 1
  39. Vector Implementation - 2
  40. Quiz: Vectors
  41. Multi-dimensional Arrays

1. What is C++? ๐Ÿค”

C++ is a powerful programming language that extends C with object-oriented features.

๐ŸŽฏ Key Points:

๐ŸŒ Real-World Analogy:

Think of C++ as a Swiss Army knife - it can do almost everything, but you need to learn how to use each tool.

โœ… Why Learn C++?

// Your first C++ program
#include <iostream>
using namespace std;

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

2. Literals ๐Ÿ’Ž

Literals are fixed values written directly in the code.

๐Ÿ“Š Types of Literals:

Type Example Description
Integer 42, -10, 0 Whole numbers
Floating 3.14, 2.5f Decimal numbers
Character 'A', 'x', '5' Single character (use single quotes)
String "Hello", "C++" Text (use double quotes)
Boolean true, false Logical values

๐Ÿ’ก Examples:

int age = 25;              // Integer literal
float pi = 3.14159;        // Floating literal
char grade = 'A';          // Character literal
string name = "John";      // String literal
bool isStudent = true;     // Boolean literal

๐ŸŽฏ Quick Trick:


3. Comments ๐Ÿ’ฌ

Comments are notes in code that the compiler ignores. They help explain your code to others (and future you!).

๐Ÿ“ Types:

// This is a single-line comment

/* This is a
   multi-line comment
   spanning multiple lines */

int x = 5;  // You can add comments after code too

โœ… Best Practices:

// โŒ BAD: This adds 2 numbers
int sum = a + b;

// โœ… GOOD: Calculate total price including 10% tax
int total = price + (price * 0.10);

4. Variables ๐Ÿ“ฆ

Variables are containers that store data. Think of them as labeled boxes.

๐ŸŽฏ Declaration & Initialization:

// Declaration (creating the box)
int age;

// Initialization (putting value in the box)
age = 20;

// Declaration + Initialization (combined)
int score = 100;

// Multiple variables of same type
int x = 5, y = 10, z = 15;

๐Ÿ“ Naming Rules:

๐ŸŽจ Naming Conventions:

// Good names (descriptive)
int studentAge;
float accountBalance;
string userName;

// Bad names (unclear)
int x;
float f;
string s;

๐Ÿ’ก Quick Tips:


5. Data Types ๐Ÿ—‚๏ธ

Data types define what kind of data a variable can hold.

๐Ÿ“Š Common Data Types:

Type Size Range Example
int 4 bytes -2 billion to +2 billion int age = 25;
float 4 bytes 6-7 decimal digits float pi = 3.14f;
double 8 bytes 15 decimal digits double price = 99.99;
char 1 byte Single character char grade = 'A';
bool 1 byte true or false bool isValid = true;
string varies Text string name = "John";

๐ŸŒณ Type Tree:

flowchart TD A[Data Types] --> B[Primitive] A --> C[Derived] B --> D[int - whole numbers] B --> E[float - decimals] B --> F[double - larger decimals] B --> G[char - single character] B --> H[bool - true/false] C --> I[string - text] C --> J[array - collection] C --> K[pointer - address]

๐Ÿ’ก When to Use What?

int age = 25;              // Whole numbers (age, count, quantity)
float temperature = 36.5;  // Precision doesn't matter much
double bankBalance = 1234567.89;  // Need high precision
char initial = 'J';        // Single character
bool isPassed = true;      // Yes/No, True/False situations
string message = "Hello";  // Text, names, sentences

๐ŸŽฏ Memory Tip:

Size matters! Choose the smallest type that fits your needs to save memory.


6. Print Output ๐Ÿ–จ๏ธ

Printing shows data on the screen using cout.

๐Ÿ“ค Basic Syntax:

#include <iostream>
using namespace std;

int main() {
    cout << "Hello World";
    return 0;
}

๐Ÿ”— Chaining Output:

int age = 25;
string name = "John";

// Multiple items in one line
cout << "Name: " << name << ", Age: " << age;

Output:

Name: John, Age: 25

๐Ÿ“ Escape Sequences:

Sequence Meaning Example
\n New line cout << "Hello\nWorld";
\t Tab space cout << "Name:\tJohn";
\\ Backslash cout << "C:\\Users";
\" Double quote cout << "She said \"Hi\"";

๐Ÿ’ก Examples:

// New line method 1
cout << "Line 1" << endl;
cout << "Line 2" << endl;

// New line method 2 (faster)
cout << "Line 1\n";
cout << "Line 2\n";

// Formatting
cout << "Name:\t\tJohn\n";
cout << "Age:\t\t25\n";
cout << "City:\t\tNew York\n";

7. Operators Part 1 โž•โž–

Arithmetic Operators perform mathematical operations.

๐Ÿ“Š Arithmetic Operators:

Operator Name Example Result
+ Addition 5 + 3 8
- Subtraction 5 - 3 2
* Multiplication 5 * 3 15
/ Division 6 / 3 2
% Modulus (remainder) 7 % 3 1

๐Ÿ’ก Examples:

int a = 10, b = 3;

cout << a + b;  // 13
cout << a - b;  // 7
cout << a * b;  // 30
cout << a / b;  // 3 (integer division!)
cout << a % b;  // 1 (remainder)

โš ๏ธ Integer Division Gotcha:

int result1 = 7 / 2;      // 3 (not 3.5!)
float result2 = 7.0 / 2;  // 3.5 (correct)

๐Ÿ“Š Assignment Operators:

Operator Example Same As
= x = 5 x = 5
+= x += 3 x = x + 3
-= x -= 3 x = x - 3
*= x *= 3 x = x * 3
/= x /= 3 x = x / 3
%= x %= 3 x = x % 3

๐ŸŽฏ Increment/Decrement:

int x = 5;

x++;    // x = 6 (post-increment)
++x;    // x = 7 (pre-increment)
x--;    // x = 6 (post-decrement)
--x;    // x = 5 (pre-decrement)

// Difference between pre and post
int a = 5;
int b = a++;  // b = 5, a = 6 (use then increment)
int c = ++a;  // c = 7, a = 7 (increment then use)

๐Ÿ” Dry Run: Pre vs Post Increment

Code: int a = 5; int b = a++; int c = ++a;

Step 1: int a = 5;          โ†’ a = 5
Step 2: int b = a++;        โ†’ b = 5 (copy a first), then a = 6
Step 3: int c = ++a;        โ†’ a = 7 (increment first), then c = 7

Final values: a = 7, b = 5, c = 7

8. Operators Part 2 ๐Ÿ”

Comparison & Logical Operators help make decisions.

๐Ÿ“Š Comparison Operators:

Operator Meaning Example Result
== Equal to 5 == 5 true
!= Not equal to 5 != 3 true
> Greater than 5 > 3 true
< Less than 5 < 3 false
>= Greater or equal 5 >= 5 true
<= Less or equal 5 <= 3 false

๐Ÿ’ก Examples:

int age = 18;

bool isAdult = (age >= 18);      // true
bool isTeenager = (age < 20);    // true
bool isExact = (age == 18);      // true

๐Ÿ“Š Logical Operators:

Operator Name Description Example
&& AND True if BOTH are true (a > 0) && (b > 0)
|| OR True if ANY is true (a > 0) || (b > 0)
! NOT Reverses the result !(a > 0)

๐ŸŽฏ Truth Tables:

AND (&&) - Both must be true:

true  && true  = true
true  && false = false
false && true  = false
false && false = false

OR (||) - At least one must be true:

true  || true  = true
true  || false = true
false || true  = true
false || false = false

NOT (!) - Reverses:

!true  = false
!false = true

๐Ÿ’ก Real Examples:

int age = 20;
bool hasLicense = true;

// Can drive if age >= 18 AND has license
bool canDrive = (age >= 18) && hasLicense;  // true

// Weekend if Saturday OR Sunday
bool isSaturday = true;
bool isSunday = false;
bool isWeekend = isSaturday || isSunday;  // true

// Not a weekday
bool isWeekday = !isWeekend;  // false

๐Ÿ” Dry Run: Logical Operators

Code: int age = 20; bool hasLicense = true;
      bool canDrive = (age >= 18) && hasLicense;

Step 1: age = 20, hasLicense = true
Step 2: Evaluate (age >= 18) โ†’ (20 >= 18) = true
Step 3: Evaluate true && true = true
Step 4: canDrive = true

Code: bool isSaturday = true; bool isSunday = false;
      bool isWeekend = isSaturday || isSunday;

Step 1: isSaturday = true, isSunday = false
Step 2: Evaluate true || false = true
Step 3: isWeekend = true

Code: bool isWeekday = !isWeekend;

Step 1: isWeekend = true
Step 2: Evaluate !true = false
Step 3: isWeekday = false

โšก Operator Precedence (Order):

1. !           (NOT)
2. *, /, %     (Multiply, Divide, Modulus)
3. +, -        (Add, Subtract)
4. <, >, <=, >= (Comparison)
5. ==, !=      (Equality)
6. &&          (AND)
7. ||          (OR)

9. Booleans โœ…โŒ

Booleans represent true or false values.

๐ŸŽฏ Basic Concept:

bool isRaining = true;
bool isSunny = false;

Output:

1 (true = 1)
0 (false = 0)

๐Ÿ’ก Boolean Expressions:

int score = 85;

bool passed = (score >= 60);        // true
bool perfect = (score == 100);      // false
bool failed = (score < 60);         // false

๐ŸŒ Real-World Uses:

// Login system
bool isLoggedIn = false;
bool hasPermission = true;

// Game state
bool isGameOver = false;
bool playerAlive = true;

// Form validation
bool isEmailValid = true;
bool isPasswordStrong = false;

๐ŸŽฏ Quick Facts:


10. If-Else ๐Ÿ”€

If-Else makes decisions in your code.

๐Ÿ“ Syntax:

if (condition) {
    // Code runs if condition is TRUE
} else {
    // Code runs if condition is FALSE
}

๐ŸŒณ Flow Diagram:

flowchart TD A[Start] --> B{Condition?} B -->|True| C[If Block] B -->|False| D[Else Block] C --> E[End] D --> E

๐Ÿ’ก Examples:

// Example 1: Simple check
int age = 20;

if (age >= 18) {
    cout << "You are an adult";
} else {
    cout << "You are a minor";
}

// Example 2: Multiple conditions
int score = 85;

if (score >= 90) {
    cout << "Grade: A";
} else {
    cout << "Grade: Not A";
}

// Example 3: Without else (optional)
bool isRaining = true;

if (isRaining) {
    cout << "Take an umbrella!";
}
// If false, nothing happens

๐ŸŽฏ When to Use:

โšก Shorthand (Ternary Operator):

// Normal if-else
int age = 20;
string status;
if (age >= 18) {
    status = "Adult";
} else {
    status = "Minor";
}

// Shorthand (same thing!)
string status = (age >= 18) ? "Adult" : "Minor";
//              ^condition^   ^true^   ^false^

11. Else-If Ladder ๐Ÿชœ

Else-If Ladder handles multiple conditions in order.

๐Ÿ“ Syntax:

if (condition1) {
    // Runs if condition1 is true
} else if (condition2) {
    // Runs if condition2 is true
} else if (condition3) {
    // Runs if condition3 is true
} else {
    // Runs if ALL above are false
}

๐ŸŒณ Flow Diagram:

flowchart TD A[Start] --> B{Condition 1?} B -->|Yes| C[Code Block 1] B -->|No| D{Condition 2?} D -->|Yes| E[Code Block 2] D -->|No| F{Condition 3?} F -->|Yes| G[Code Block 3] F -->|No| H[Else Block] C --> I[End] E --> I G --> I H --> I

๐Ÿ’ก Examples:

// Example 1: Grade System
int marks = 85;

if (marks >= 90) {
    cout << "Grade: A+";
} else if (marks >= 80) {
    cout << "Grade: A";
} else if (marks >= 70) {
    cout << "Grade: B";
} else if (marks >= 60) {
    cout << "Grade: C";
} else {
    cout << "Grade: F";
}

๐Ÿ” Dry Run: Else-If Ladder (Grade System)

Code: int marks = 85;
      if (marks >= 90) { ... }
      else if (marks >= 80) { ... }
      else if (marks >= 70) { ... }
      else if (marks >= 60) { ... }
      else { ... }

Step 1: marks = 85
Step 2: Check marks >= 90? โ†’ 85 >= 90 = false โ†’ Skip this block
Step 3: Check marks >= 80? โ†’ 85 >= 80 = true โ†’ Execute this block
Step 4: Print "Grade: A"
Step 5: Exit (remaining conditions are skipped)

Output: Grade: A
// Example 2: Traffic Light
string light = "yellow";

if (light == "red") {
    cout << "STOP!";
} else if (light == "yellow") {
    cout << "SLOW DOWN";
} else if (light == "green") {
    cout << "GO";
} else {
    cout << "Light broken!";
}

// Example 3: Age Categories
int age = 25;

if (age < 13) {
    cout << "Child";
} else if (age < 20) {
    cout << "Teenager";
} else if (age < 60) {
    cout << "Adult";
} else {
    cout << "Senior";
}

๐ŸŽฏ Important Rules:

๐Ÿ’ก Quick Tip:

Put the most likely condition first for better performance!


12. While Loop ๐Ÿ”„

While Loop repeats code as long as a condition is true.

๐Ÿ“ Syntax:

while (condition) {
    // Code to repeat
    // Update condition (important!)
}

๐ŸŒณ Flow Diagram:

flowchart TD A[Start] --> B{Condition?} B -->|True| C[Loop Body] C --> D[Update] D --> B B -->|False| E[End]

๐Ÿ’ก Examples:

// Example 1: Count from 1 to 5
int i = 1;
while (i <= 5) {
    cout << i << " ";
    i++;  // MUST update!
}

Output:

1 2 3 4 5
int n = 10;
int sum = 0;
int i = 1;
while (i <= n) {
sum = sum + i;
i++;
}
cout << "Sum = " << sum;   55

๐Ÿ” Dry Run: Sum of Numbers (1 to 10)

Code: int n = 10; int sum = 0; int i = 1;
      while (i <= n) { sum = sum + i; i++; }

Initial: n = 10, sum = 0, i = 1

Iteration 1: i = 1 โ‰ค 10? YES โ†’ sum = 0 + 1 = 1,  i = 2
Iteration 2: i = 2 โ‰ค 10? YES โ†’ sum = 1 + 2 = 3,  i = 3
Iteration 3: i = 3 โ‰ค 10? YES โ†’ sum = 3 + 3 = 6,  i = 4
Iteration 4: i = 4 โ‰ค 10? YES โ†’ sum = 6 + 4 = 10, i = 5
Iteration 5: i = 5 โ‰ค 10? YES โ†’ sum = 10 + 5 = 15, i = 6
Iteration 6: i = 6 โ‰ค 10? YES โ†’ sum = 15 + 6 = 21, i = 7
Iteration 7: i = 7 โ‰ค 10? YES โ†’ sum = 21 + 7 = 28, i = 8
Iteration 8: i = 8 โ‰ค 10? YES โ†’ sum = 28 + 8 = 36, i = 9
Iteration 9: i = 9 โ‰ค 10? YES โ†’ sum = 36 + 9 = 45, i = 10
Iteration 10: i = 10 โ‰ค 10? YES โ†’ sum = 45 + 10 = 55, i = 11
Iteration 11: i = 11 โ‰ค 10? NO โ†’ Loop exits

Final: sum = 55
// Example 3: User input validation
int password;
while (password != 1234) {
    cout << "Enter password: ";
    cin >> password;
}
cout << "Access granted!";

โš ๏ธ Infinite Loop Warning:

// DANGER! This never stops
int i = 1;
while (i <= 5) {
    cout << i;
    // Forgot i++; 
    // Loop runs FOREVER!
}

๐ŸŽฏ When to Use:


13. For Loop ๐Ÿ”

For Loop is perfect when you know how many times to repeat.

๐Ÿ“ Syntax:

for (initialization; condition; update) {
    // Code to repeat
}

๐Ÿงฉ Parts Explained:

for (int i = 0; i < 5; i++) {
//       ^         ^      ^
//       |         |      |___ 3. Update (after each loop)
//       |         |__________ 2. Condition (check before each loop)
//       |____________________ 1. Initialization (runs once)
}

๐ŸŒณ Flow Diagram:

flowchart TD A[Initialize] --> B{Condition?} B -->|True| C[Loop Body] C --> D[Update] D --> B B -->|False| E[Exit Loop]

๐Ÿ’ก Examples:

// Example 1: Print 1 to 5
for (int i = 1; i <= 5; i++) {
    cout << i << " ";
}

Output:

1 2 3 4 5

๐Ÿ” Dry Run: For Loop (Print 1 to 5)

Code: for (int i = 1; i <= 5; i++) { cout << i << " "; }

Step 1: Initialize i = 1
Step 2: Check condition 1 โ‰ค 5? YES โ†’ Print 1, i++ โ†’ i = 2
Step 3: Check condition 2 โ‰ค 5? YES โ†’ Print 2, i++ โ†’ i = 3
Step 4: Check condition 3 โ‰ค 5? YES โ†’ Print 3, i++ โ†’ i = 4
Step 5: Check condition 4 โ‰ค 5? YES โ†’ Print 4, i++ โ†’ i = 5
Step 6: Check condition 5 โ‰ค 5? YES โ†’ Print 5, i++ โ†’ i = 6
Step 7: Check condition 6 โ‰ค 5? NO โ†’ Loop exits

Output: 1 2 3 4 5
// Example 2: Countdown
for (int i = 10; i >= 1; i--) {
    cout << i << " ";
}
cout << "Blast off!";

Output:

10 9 8 7 6 5 4 3 2 1 Blast off!
for (int i = 0; i <= 10; i += 2) {
cout << i << " ";
}
0 2 4 6 8 10
int n = 5;
for (int i = 1; i <= 10; i++) {
cout << n << " x " << i << " = " << n * i << endl;
}

๐Ÿ“Š For vs While:

For Loop While Loop
Know exact iterations Unknown iterations
for (int i=0; i<10; i++) while (condition)
Counter-based Condition-based
Cleaner for counting Better for validation

๐ŸŽฏ Quick Pattern:

// Pattern: 0 to N-1 (most common!)
for (int i = 0; i < n; i++) { }

// Pattern: 1 to N
for (int i = 1; i <= n; i++) { }

// Pattern: Reverse
for (int i = n; i >= 1; i--) { }

14. Loops Standard Problems ๐Ÿงฎ

Common problems solved with loops.

1๏ธโƒฃ Sum of N Numbers

// Sum from 1 to n
int n = 10;
int sum = 0;

for (int i = 1; i <= n; i++) {
    sum += i;
}
cout << "Sum = " << sum;  // 55

2๏ธโƒฃ Factorial

// 5! = 5 ร— 4 ร— 3 ร— 2 ร— 1 = 120
int n = 5;
int factorial = 1;

for (int i = 1; i <= n; i++) {
    factorial *= i;
}
cout << "Factorial = " << factorial;  // 120

๐Ÿ” Dry Run: Factorial of 5

Code: int n = 5; int factorial = 1;
      for (int i = 1; i <= n; i++) { factorial *= i; }

Initial: n = 5, factorial = 1

Iteration 1: i = 1 โ†’ factorial = 1 ร— 1 = 1
Iteration 2: i = 2 โ†’ factorial = 1 ร— 2 = 2
Iteration 3: i = 3 โ†’ factorial = 2 ร— 3 = 6
Iteration 4: i = 4 โ†’ factorial = 6 ร— 4 = 24
Iteration 5: i = 5 โ†’ factorial = 24 ร— 5 = 120

Final: factorial = 120

3๏ธโƒฃ Print Patterns

// Pattern 1: Square
// * * * *
// * * * *
// * * * *
// * * * *

for (int i = 1; i <= 4; i++) {
    for (int j = 1; j <= 4; j++) {
        cout << "* ";
    }
    cout << endl;
}

// Pattern 2: Right Triangle
// *
// * *
// * * *
// * * * *

for (int i = 1; i <= 4; i++) {
    for (int j = 1; j <= i; j++) {
        cout << "* ";
    }
    cout << endl;
}

// Pattern 3: Numbers
// 1
// 1 2
// 1 2 3
// 1 2 3 4

for (int i = 1; i <= 4; i++) {
    for (int j = 1; j <= i; j++) {
        cout << j << " ";
    }
    cout << endl;
}

4๏ธโƒฃ Reverse a Number

int num = 1234;
int reversed = 0;

while (num > 0) {
    int digit = num % 10;      // Get last digit
    reversed = reversed * 10 + digit;
    num = num / 10;            // Remove last digit
}
cout << reversed;  // 4321

๐Ÿ” Dry Run: Reverse Number (1234)

Code: int num = 1234; int reversed = 0;
      while (num > 0) {
          int digit = num % 10;
          reversed = reversed * 10 + digit;
          num = num / 10;
      }

Initial: num = 1234, reversed = 0

Iteration 1:
  digit = 1234 % 10 = 4
  reversed = 0 ร— 10 + 4 = 4
  num = 1234 / 10 = 123

Iteration 2:
  digit = 123 % 10 = 3
  reversed = 4 ร— 10 + 3 = 43
  num = 123 / 10 = 12

Iteration 3:
  digit = 12 % 10 = 2
  reversed = 43 ร— 10 + 2 = 432
  num = 12 / 10 = 1

Iteration 4:
  digit = 1 % 10 = 1
  reversed = 432 ร— 10 + 1 = 4321
  num = 1 / 10 = 0

Iteration 5: num = 0 โ†’ Loop exits

Final: reversed = 4321

5๏ธโƒฃ Count Digits

int num = 12345;
int count = 0;

while (num > 0) {
    count++;
    num = num / 10;
}
cout << "Digits: " << count;  // 5

6๏ธโƒฃ Check Prime Number

int n = 17;
bool isPrime = true;

for (int i = 2; i < n; i++) {
    if (n % i == 0) {
        isPrime = false;
        break;
    }
}

if (isPrime && n > 1) {
    cout << n << " is prime";
}

7๏ธโƒฃ Fibonacci Series

// 0, 1, 1, 2, 3, 5, 8, 13...
int n = 10;
int a = 0, b = 1;

cout << a << " " << b << " ";

for (int i = 2; i < n; i++) {
    int next = a + b;
    cout << next << " ";
    a = b;
    b = next;
}

๐Ÿ” Dry Run: Fibonacci Series (First 7 terms)

Code: int n = 7; int a = 0, b = 1;
      cout << a << " " << b << " ";
      for (int i = 2; i < n; i++) {
          int next = a + b;
          cout << next << " ";
          a = b; b = next;
      }

Initial: n = 7, a = 0, b = 1
Print: 0 1

Iteration 1 (i=2):
  next = 0 + 1 = 1 โ†’ Print: 1
  a = 1, b = 1

Iteration 2 (i=3):
  next = 1 + 1 = 2 โ†’ Print: 2
  a = 1, b = 2

Iteration 3 (i=4):
  next = 1 + 2 = 3 โ†’ Print: 3
  a = 2, b = 3

Iteration 4 (i=5):
  next = 2 + 3 = 5 โ†’ Print: 5
  a = 3, b = 5

Iteration 5 (i=6):
  next = 3 + 5 = 8 โ†’ Print: 8
  a = 5, b = 8

Iteration 6: i = 7 โ†’ Loop exits

Output: 0 1 1 2 3 5 8

15. Break and Continue โญ๏ธ

Break exits the loop, Continue skips to next iteration.

๐Ÿ›‘ Break Statement

Stops the loop completely and exits.

// Example 1: Exit when found
for (int i = 1; i <= 10; i++) {
    if (i == 5) {
        break;  // Stop here!
    }
    cout << i << " ";
}

Output:

1 2 3 4

๐Ÿ” Dry Run: Break Statement

Code: for (int i = 1; i <= 10; i++) {
          if (i == 5) { break; }
          cout << i << " ";
      }

Iteration 1: i = 1 โ†’ Check i == 5? NO โ†’ Print 1
Iteration 2: i = 2 โ†’ Check i == 5? NO โ†’ Print 2
Iteration 3: i = 3 โ†’ Check i == 5? NO โ†’ Print 3
Iteration 4: i = 4 โ†’ Check i == 5? NO โ†’ Print 4
Iteration 5: i = 5 โ†’ Check i == 5? YES โ†’ break โ†’ Exit loop

Output: 1 2 3 4
// Example 2: Search in array
int arr[] = {10, 20, 30, 40, 50};
int target = 30;
bool found = false;

for (int i = 0; i < 5; i++) {
    if (arr[i] == target) {
        found = true;
        break;  // No need to check further
    }
}

โญ๏ธ Continue Statement

Skips current iteration and goes to next one.

// Example 1: Skip even numbers
for (int i = 1; i <= 10; i++) {
    if (i % 2 == 0) {
        continue;  // Skip rest of code
    }
    cout << i << " ";
}

Output:

1 3 5 7 9

๐Ÿ” Dry Run: Continue Statement

Code: for (int i = 1; i <= 6; i++) {
          if (i % 2 == 0) { continue; }
          cout << i << " ";
      }

Iteration 1: i = 1 โ†’ Check 1 % 2 == 0? NO โ†’ Print 1
Iteration 2: i = 2 โ†’ Check 2 % 2 == 0? YES โ†’ continue โ†’ Skip print
Iteration 3: i = 3 โ†’ Check 3 % 2 == 0? NO โ†’ Print 3
Iteration 4: i = 4 โ†’ Check 4 % 2 == 0? YES โ†’ continue โ†’ Skip print
Iteration 5: i = 5 โ†’ Check 5 % 2 == 0? NO โ†’ Print 5
Iteration 6: i = 6 โ†’ Check 6 % 2 == 0? YES โ†’ continue โ†’ Skip print

Output: 1 3 5
// Example 2: Skip negative numbers
int arr[] = {5, -2, 8, -1, 10};

for (int i = 0; i < 5; i++) {
    if (arr[i] < 0) {
        continue;  // Skip negative
    }
    cout << arr[i] << " ";
}

Output:

5 8 10

๐Ÿ“Š Break vs Continue:

Break Continue
Exits the loop Skips current iteration
Loop stops completely Loop continues with next iteration
Use when done searching Use when skipping certain values

๐ŸŒณ Visual Flow:

BREAK:

flowchart LR A[Loop] --> B{Condition} B -->|break!| C[EXIT LOOP]

CONTINUE:

flowchart LR A[Loop] --> B{Condition} B -->|continue!| C[NEXT ITERATION] C --> A

๐Ÿ’ก Real-World Examples:

// Login attempts (break after success)
int attempts = 0;
while (attempts < 3) {
    int password;
    cout << "Enter password: ";
    cin >> password;

    if (password == 1234) {
        cout << "Access granted!";
        break;  // Stop asking
    }
    attempts++;
}

// Process only valid data (continue for invalid)
for (int i = 0; i < 10; i++) {
    if (data[i] == 0) {
        continue;  // Skip zero values
    }
    processData(data[i]);
}

16. Switch Statement ๐Ÿ”€

Switch handles multiple specific values efficiently.

๐Ÿ“ Syntax:

switch (variable) {
    case value1:
        // Code
        break;
    case value2:
        // Code
        break;
    default:
        // Code if no match
}

๐Ÿ’ก Examples:

// Example 1: Days of week
int day = 3;

switch (day) {
    case 1:
        cout << "Monday";
        break;
    case 2:
        cout << "Tuesday";
        break;
    case 3:
        cout << "Wednesday";
        break;
    case 4:
        cout << "Thursday";
        break;
    case 5:
        cout << "Friday";
        break;
    case 6:
        cout << "Saturday";
        break;
    case 7:
        cout << "Sunday";
        break;
    default:
        cout << "Invalid day";
}

// Example 2: Calculator
char op = '+';
int a = 10, b = 5;

switch (op) {
    case '+':
        cout << a + b;
        break;
    case '-':
        cout << a - b;
        break;
    case '*':
        cout << a * b;
        break;
    case '/':
        cout << a / b;
        break;
    default:
        cout << "Invalid operator";
}

// Example 3: Grade evaluation
char grade = 'B';

switch (grade) {
    case 'A':
        cout << "Excellent!";
        break;
    case 'B':
        cout << "Good job!";
        break;
    case 'C':
        cout << "Well done!";
        break;
    case 'D':
        cout << "You passed!";
        break;
    case 'F':
        cout << "Better luck next time";
        break;
    default:
        cout << "Invalid grade";
}

โš ๏ธ Fall-through Behavior:

// WITHOUT break (fall-through)
int x = 2;

switch (x) {
    case 1:
        cout << "One ";
    case 2:
        cout << "Two ";   // Starts here
    case 3:
        cout << "Three ";  // Also runs!
}

Output:

Two Three
switch (x) {
case 1:
cout << "One";
break;
case 2:
cout << "Two";     Only this runs
break;
case 3:
cout << "Three";
break;
}
Two

๐Ÿ“Š Switch vs If-Else:

Switch If-Else
Specific exact values Any conditions
Only int, char, enum Any type
Cleaner for many values Better for ranges
case 1: if (x == 1)

๐ŸŽฏ When to Use Switch:


17. Functions ๐ŸŽฏ

Functions are reusable blocks of code that perform specific tasks.

๐Ÿ“ Basic Syntax:

returnType functionName(parameters) {
    // Code to execute
    return value;  // if not void
}

๐Ÿงฉ Anatomy of a Function:

// Function structure:
int addNumbers(int a, int b) {
//  ^      ^          ^
//  |      |          |__ Parameters (input)
//  |      |_____________ Function name
//  |____________________ Return type (output)

    int sum = a + b;
    return sum;        // Send result back
}

๐Ÿ’ก Examples:

// Example 1: Simple greeting
void greet() {
    cout << "Hello, World!";
}

// Calling the function

Output:

Hello, World!
void greetUser(string name) {
cout << "Hello, " << name << "!";
}
greetUser("John");    Hello, John!
greetUser("Sarah");   Hello, Sarah!
int square(int num) {
return num * num;
}
int result = square(5);   result = 25
cout << square(7);        49
int multiply(int a, int b) {
return a * b;
}
cout << multiply(4, 5);   20

๐ŸŒณ Function Flow:

flowchart TD A[Main Program] --> B[Call Function] B --> C[Execute Function] C --> D[Return Result] D --> E[Continue Main Program]

๐ŸŽฏ Benefits of Functions:

Benefit Description
Reusability Write once, use many times
Organization Break big problems into smaller parts
Readability Code is easier to understand
Maintenance Fix bugs in one place
Testing Test each function separately

๐Ÿ’ก Real-World Example:

// Without functions (repetitive!)
cout << "Welcome to our app!";
cout << "Please login";
// ... 50 more lines
cout << "Welcome to our app!";  // Repeated!
cout << "Please login";

// With functions (clean!)
void showWelcome() {
    cout << "Welcome to our app!";
    cout << "Please login";
}

showWelcome();  // Use anywhere!
// ... other code
showWelcome();  // Easy to reuse!

18. Function Arguments ๐Ÿ“ฅ

Arguments are values passed to functions.

๐Ÿ“Š Parameters vs Arguments:

void greet(string name) {  // 'name' is a PARAMETER
    cout << "Hello " << name;
}

greet("John");  // "John" is an ARGUMENT
Term Where What
Parameter Function definition Variable in brackets
Argument Function call Actual value passed

๐Ÿ’ก Examples:

// Example 1: Single parameter
void printSquare(int num) {
    cout << num * num;
}

printSquare(5);   // 25
printSquare(10);  // 100

// Example 2: Multiple parameters
int add(int a, int b) {
    return a + b;
}

cout << add(5, 3);      // 8
cout << add(10, 20);    // 30

// Example 3: Different types
void displayInfo(string name, int age, float height) {
    cout << "Name: " << name << endl;
    cout << "Age: " << age << endl;
    cout << "Height: " << height << endl;
}

displayInfo("John", 25, 5.9);
// Name: John
// Age: 25
// Height: 5.9

// Example 4: Default parameters
void greet(string name = "Guest") {
    cout << "Hello " << name;
}

greet("John");  // Hello John
greet();        // Hello Guest (uses default)

๐Ÿ”„ Pass by Value vs Reference:

// Pass by VALUE (copy)
void changeValue(int x) {
    x = 100;  // Only changes the copy
}

int num = 5;
changeValue(num);
cout << num;  // Still 5 (original unchanged)

// Pass by REFERENCE (original)
void changeReference(int &x) {
    x = 100;  // Changes the original!
}

int num = 5;
changeReference(num);
cout << num;  // Now 100 (original changed)

๐Ÿ“Š Comparison:

Pass by Value Pass by Reference
void func(int x) void func(int &x)
Copies the value Uses original variable
Original unchanged Original can change
Slower (copy) Faster (no copy)
Safe Use carefully

๐ŸŽฏ When to Use:

// Use pass by value for:
// - Small data (int, float, char)
// - When you don't want to change original

int calculate(int x) { }  // โœ…

// Use pass by reference for:
// - Large data (arrays, objects)
// - When you want to modify original

void swap(int &a, int &b) {  // โœ…
    int temp = a;
    a = b;
    b = temp;
}

int x = 5, y = 10;
swap(x, y);
// Now x = 10, y = 5

19. Return Statement ๐Ÿ”™

Return sends a value back from a function.

๐Ÿ“ Syntax:

returnType functionName() {
    // Code
    return value;  // Must match returnType
}

๐Ÿ’ก Examples:

// Example 1: Return integer
int getAge() {
    return 25;
}

int age = getAge();  // age = 25

// Example 2: Return calculation
int add(int a, int b) {
    return a + b;
}

int sum = add(5, 3);  // sum = 8

// Example 3: Return boolean
bool isEven(int num) {
    if (num % 2 == 0) {
        return true;
    } else {
        return false;
    }
}

// Shorter version:
bool isEven(int num) {
    return (num % 2 == 0);
}

// Example 4: Return string
string getGreeting(int hour) {
    if (hour < 12) {
        return "Good morning";
    } else if (hour < 18) {
        return "Good afternoon";
    } else {
        return "Good evening";
    }
}

cout << getGreeting(10);  // Good morning

๐Ÿšซ Void Functions (No Return):

void printMessage() {
    cout << "Hello!";
    // No return needed
}

// Can use return to exit early
void checkAge(int age) {
    if (age < 0) {
        cout << "Invalid age";
        return;  // Exit function early
    }
    cout << "Valid age";
}

๐Ÿ“Š Return Types:

Type Example Use Case
int return 5; Numbers
float return 3.14; Decimals
bool return true; Yes/No checks
string return "Hi"; Text
void (no return) Just do something

๐ŸŽฏ Multiple Returns:

// Function exits at first return
string checkGrade(int marks) {
    if (marks >= 90) {
        return "A";  // Exits here if true
    }
    if (marks >= 80) {
        return "B";  // Exits here if true
    }
    if (marks >= 70) {
        return "C";
    }
    return "F";  // Default return
}

โš ๏ธ Important Rules:

// โŒ WRONG: No return in else
int getMax(int a, int b) {
    if (a > b) {
        return a;
    }
    // Missing return! Error!
}

// โœ… CORRECT
int getMax(int a, int b) {
    if (a > b) {
        return a;
    }
    return b;  // All paths covered
}

20. Local Variable ๐Ÿ“

Local variables exist only inside the function/block where they're created.

๐ŸŽฏ Scope Concept:

void myFunction() {
    int x = 10;  // Local to myFunction
    cout << x;   // โœ… Works
}

int main() {
    myFunction();
    cout << x;   // โŒ ERROR! x doesn't exist here
}

๐ŸŒณ Visual Scope:

flowchart TD A[Global Scope] --> B[Function A] A --> C[Function B] B --> D[Local Variable A
dies when function ends] C --> E[Local Variable B
dies when function ends]

๐Ÿ’ก Examples:

// Example 1: Block scope
void example() {
    int x = 5;  // Local to function

    if (x > 0) {
        int y = 10;  // Local to if block
        cout << x;   // โœ… Can use x
        cout << y;   // โœ… Can use y
    }

    cout << x;  // โœ… Can use x
    cout << y;  // โŒ ERROR! y doesn't exist here
}

// Example 2: Loop scope
void loopExample() {
    for (int i = 0; i < 5; i++) {
        int temp = i * 2;  // Created each iteration
        cout << temp;
    }
    cout << i;     // โŒ ERROR! i is local to loop
    cout << temp;  // โŒ ERROR! temp is local to loop
}

// Example 3: Same names, different scopes
void function1() {
    int num = 10;
    cout << num;  // 10
}

void function2() {
    int num = 20;  // Different variable!
    cout << num;  // 20
}

๐Ÿ“Š Local vs Global:

Local Variable Global Variable
Inside function/block Outside all functions
Dies when scope ends Lives entire program
int x; (in function) int x; (outside all)
Can't access outside Can access anywhere
Memory freed quickly Memory used always
int globalVar = 100;  // Global

void myFunction() {
    int localVar = 50;  // Local

    cout << globalVar;  // โœ… Can use global
    cout << localVar;   // โœ… Can use local
}

int main() {
    cout << globalVar;  // โœ… Can use global
    cout << localVar;   // โŒ ERROR! Can't use local
}

๐ŸŽฏ Lifetime:

void example() {
    int x = 5;     // Created here
    cout << x;     // Exists
    // x destroyed here
}

// Call function multiple times
example();  // x created and destroyed
example();  // NEW x created and destroyed
example();  // Another NEW x created and destroyed

๐Ÿ’ก Best Practice:


21. Why Do We Use Arguments and Return Type? ๐Ÿค”

Functions with arguments and return types make code flexible, reusable, and maintainable.

๐ŸŽฏ Without Arguments & Return (Limited):

// โŒ Hard-coded, not reusable
void addNumbers() {
    int a = 5;
    int b = 10;
    int sum = a + b;
    cout << sum;
}

addNumbers();  // Always adds 5 + 10
// Can't add different numbers!

โœ… With Arguments & Return (Flexible):

// โœ… Flexible and reusable
int addNumbers(int a, int b) {
    return a + b;
}

cout << addNumbers(5, 10);    // 15
cout << addNumbers(20, 30);   // 50
cout << addNumbers(100, 200); // 300
// Same function, different values!

๐Ÿ’ก Benefits:

1๏ธโƒฃ Reusability

// One function, many uses
int square(int n) {
    return n * n;
}

int area1 = square(5);   // 25
int area2 = square(10);  // 100
int area3 = square(15);  // 225

2๏ธโƒฃ Flexibility

// Adapt to different situations
double calculatePrice(double price, double tax) {
    return price + (price * tax);
}

double item1 = calculatePrice(100, 0.10);  // $110
double item2 = calculatePrice(50, 0.05);   // $52.50

3๏ธโƒฃ Modularity (Building Blocks)

// Combine functions like LEGO
int add(int a, int b) { return a + b; }
int multiply(int a, int b) { return a * b; }

// Build complex operations
int result = multiply(add(2, 3), 4);  // (2+3) * 4 = 20

4๏ธโƒฃ Return Values Can Be Used Anywhere

int getAge() { return 25; }

// Use in conditions
if (getAge() >= 18) {
    cout << "Adult";
}

// Use in calculations
int years = 2024 - getAge();

// Use in other functions
checkAge(getAge());

5๏ธโƒฃ Testability

// Easy to test with different inputs
bool isPrime(int n) {
    // Check if prime
    return result;
}

// Test multiple cases
cout << isPrime(2);   // true
cout << isPrime(4);   // false
cout << isPrime(17);  // true

๐Ÿ“Š Comparison:

Without With Arguments & Return
Hard-coded values Flexible inputs
Can't reuse easily Highly reusable
Limited functionality Powerful combinations
Hard to test Easy to test
Lots of duplicate code DRY (Don't Repeat Yourself)

๐ŸŒ Real-World Analogy:

Function without arguments: A vending machine that only dispenses one product.

Function with arguments: A vending machine where you choose what you want (input) and get it back (return).

// Like a vending machine
item getProduct(int code, double money) {
    // Input: product code and money

Output:

your product
return selectedItem;
}

22. Standard Library Functions ๐Ÿ“š

C++ provides built-in functions in the Standard Library.

๐Ÿ”ข Math Functions (<cmath>):

#include <cmath>

// Power and roots
pow(2, 3);     // 2^3 = 8
sqrt(16);      // 4
cbrt(27);      // 3 (cube root)

// Rounding
ceil(4.3);     // 5 (round up)
floor(4.7);    // 4 (round down)
round(4.5);    // 5 (round nearest)

// Absolute value
abs(-5);       // 5
fabs(-3.14);   // 3.14 (float absolute)

// Trigonometry
sin(0);        // 0
cos(0);        // 1
tan(0);        // 0

// Min/Max
max(5, 10);    // 10
min(5, 10);    // 5

๐Ÿ’ก Math Examples:

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

int main() {
    // Calculate area of circle
    double radius = 5;
    double area = M_PI * pow(radius, 2);
    cout << "Area: " << area << endl;

    // Distance between two points
    int x1 = 0, y1 = 0;
    int x2 = 3, y2 = 4;
    double distance = sqrt(pow(x2-x1, 2) + pow(y2-y1, 2));
    cout << "Distance: " << distance << endl;  // 5

    return 0;
}

๐Ÿ”ค String Functions (<string>):

#include <string>

string str = "Hello World";

// Length
str.length();      // 11
str.size();        // 11 (same as length)

// Access characters
str[0];            // 'H'
str.at(1);         // 'e' (safer, checks bounds)

// Modify
str.append("!");   // "Hello World!"
str.insert(5, " Beautiful");  // "Hello Beautiful World"
str.erase(0, 6);   // "World"
str.replace(0, 5, "Earth");  // "Earth"

// Search
str.find("World"); // 6 (position)
str.find("xyz");   // string::npos (not found)

// Substrings
str.substr(0, 5);  // "Hello" (from 0, length 5)

// Compare
str.compare("Hello");  // 0 if equal

๐Ÿงฎ Utility Functions (<algorithm>):

#include <algorithm>

// Min/Max
max(5, 10);        // 10
min(5, 10);        // 5

// Swap
int a = 5, b = 10;
swap(a, b);        // a=10, b=5

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

// Reverse
reverse(arr, arr + 5);  // {9, 8, 5, 2, 1}

๐Ÿ“Š Common Libraries:

Library Use For Example
<iostream> Input/Output cout, cin
<cmath> Math operations sqrt(), pow()
<string> String operations length(), substr()
<algorithm> Sorting, searching sort(), reverse()
<vector> Dynamic arrays push_back(), pop_back()
<ctime> Date and time time(), clock()

๐ŸŽฏ Quick Reference:

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

int main() {
    // Math
    cout << sqrt(16);        // 4
    cout << pow(2, 3);       // 8

    // String
    string name = "John";
    cout << name.length();   // 4

    // Algorithm
    cout << max(5, 10);      // 10

    return 0;
}

๐Ÿ’ก Tip:

You don't need to write everything from scratch! Use these built-in functions to save time and avoid bugs.


23. Nested Functions ๐Ÿช†

Nested functions means calling one function from inside another function.

๐ŸŽฏ Basic Concept:

// Function A calls Function B
int functionB() {
    return 10;
}

int functionA() {
    int result = functionB();  // Calling B from A
    return result * 2;
}

int main() {
    cout << functionA();  // 20
}

๐ŸŒณ Call Flow:

flowchart TD A[main] --> B[functionA] B --> C[functionB] C -->|returns 10| B B -->|returns 20| A A --> D[prints 20]

๐Ÿ’ก Examples:

// Example 1: Mathematical operations
int square(int n) {
    return n * n;
}

int sumOfSquares(int a, int b) {
    return square(a) + square(b);  // Calling square() twice
}

cout << sumOfSquares(3, 4);  // 3ยฒ + 4ยฒ = 9 + 16 = 25

// Example 2: Validation
bool isPositive(int n) {
    return n > 0;
}

bool isEven(int n) {
    return n % 2 == 0;
}

bool isPositiveEven(int n) {
    return isPositive(n) && isEven(n);  // Both functions!
}

cout << isPositiveEven(4);   // true
cout << isPositiveEven(-4);  // false
cout << isPositiveEven(5);   // false

// Example 3: Complex calculation
int add(int a, int b) {
    return a + b;
}

int multiply(int a, int b) {
    return a * b;
}

int calculate(int a, int b, int c) {
    return multiply(add(a, b), c);  // (a + b) * c
}

cout << calculate(2, 3, 4);  // (2+3)*4 = 20

๐Ÿ”„ Recursive Functions (Function Calls Itself):

// Factorial using recursion
int factorial(int n) {
    if (n <= 1) {
        return 1;  // Base case
    }
    return n * factorial(n - 1);  // Calls itself!
}

cout << factorial(5);
// 5 * factorial(4)
//     4 * factorial(3)
//         3 * factorial(2)
//             2 * factorial(1)
//                 returns 1
// = 5 * 4 * 3 * 2 * 1 = 120

๐Ÿ“Š Benefits of Nested Functions:

Benefit Example
Modularity Break complex tasks into smaller parts
Reusability Use same function in multiple places
Readability Code is easier to understand
Maintainability Fix bugs in one place

๐Ÿ’ก Real-World Example:

// Area of circle
double square(double n) {
    return n * n;
}

double circleArea(double radius) {
    return 3.14159 * square(radius);  // Uses square()
}

// Volume of cylinder
double cylinderVolume(double radius, double height) {
    return circleArea(radius) * height;  // Uses circleArea()
}

cout << cylinderVolume(5, 10);
// circleArea(5) = 78.54
// 78.54 * 10 = 785.4

โš ๏ธ Important Note:

In C++, you cannot define a function inside another function. But you can call any function from any other function.

// โŒ WRONG: Can't define inside
void outer() {
    void inner() {  // ERROR!
        cout << "Hi";
    }
}

// โœ… CORRECT: Define separately, call from inside
void inner() {
    cout << "Hi";
}

void outer() {
    inner();  // โœ… This works!
}

24. Arrays ๐Ÿ“š

Arrays store multiple values of the same type in a single variable.

๐ŸŽฏ Think of it as:

A row of boxes, each holding one value, numbered starting from 0.

Index:   0   1   2   3   4
Array: [10][20][30][40][50]

๐Ÿ“ Declaration & Initialization:

// Method 1: Declare then assign
int numbers[5];          // Array of 5 integers
numbers[0] = 10;
numbers[1] = 20;

// Method 2: Declare with values
int numbers[5] = {10, 20, 30, 40, 50};

// Method 3: Auto size
int numbers[] = {10, 20, 30, 40, 50};  // Size = 5 automatically

// Method 4: Partial initialization
int numbers[5] = {10, 20};  // {10, 20, 0, 0, 0} (rest are 0)

// Method 5: All zeros
int numbers[5] = {0};  // {0, 0, 0, 0, 0}

๐Ÿ”ข Accessing Elements:

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

// Access by index (0-based)
cout << numbers[0];  // 10 (first element)
cout << numbers[4];  // 50 (last element)

// Modify elements
numbers[2] = 100;  // {10, 20, 100, 40, 50}

// Use in expressions
int sum = numbers[0] + numbers[1];  // 30

๐Ÿ“Š Array Index Visualization:

Array: numbers[5] = {10, 20, 30, 40, 50}

Index:     0    1    2    3    4
Value:    10   20   30   40   50
         โ†‘                      โ†‘
       First                 Last
   numbers[0]           numbers[4]

๐Ÿ’ก Examples:

// Example 1: Student scores
int scores[5] = {85, 90, 78, 92, 88};
cout << "First score: " << scores[0];  // 85
cout << "Last score: " << scores[4];   // 88

// Example 2: Days in months
int daysInMonth[12] = {31, 28, 31, 30, 31, 30, 
                       31, 31, 30, 31, 30, 31};
cout << "Days in January: " << daysInMonth[0];   // 31
cout << "Days in February: " << daysInMonth[1];  // 28

// Example 3: Character array
char vowels[5] = {'a', 'e', 'i', 'o', 'u'};
cout << vowels[2];  // 'i'

๐ŸŽฏ Key Points:

int arr[3] = {10, 20, 30};

cout << arr[0];   // โœ… Valid (10)
cout << arr[2];   // โœ… Valid (30)
cout << arr[3];   // โŒ DANGER! Out of bounds (undefined behavior)
cout << arr[-1];  // โŒ DANGER! Out of bounds

๐Ÿ“ Getting Array Size:

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

// Get size in bytes
int sizeInBytes = sizeof(numbers);  // 20 (5 * 4 bytes)

// Get number of elements
int length = sizeof(numbers) / sizeof(numbers[0]);  // 5

cout << "Array has " << length << " elements";

25. Iterating and Updating Arrays ๐Ÿ”„

Looping through arrays to access or modify all elements.

๐Ÿ” Basic Iteration with For Loop:

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

// Print all elements
for (int i = 0; i < 5; i++) {
    cout << numbers[i] << " ";
}

Output:

10 20 30 40 50

๐ŸŒณ Loop Flow:

i = 0: numbers[0] = 10
i = 1: numbers[1] = 20
i = 2: numbers[2] = 30
i = 3: numbers[3] = 40
i = 4: numbers[4] = 50
i = 5: STOP (i < 5 is false)

๐Ÿ’ก Updating Elements:

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

// Double all elements
for (int i = 0; i < 5; i++) {
    numbers[i] = numbers[i] * 2;
}
// Result: {2, 4, 6, 8, 10}

// Add 10 to all elements
for (int i = 0; i < 5; i++) {
    numbers[i] += 10;
}
// Result: {12, 14, 16, 18, 20}

๐Ÿ“Š Common Operations:

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

// 1. Sum of all elements
int sum = 0;
for (int i = 0; i < 5; i++) {
    sum += arr[i];
}
cout << "Sum: " << sum;  // 150

๐Ÿ” Dry Run: Array Sum

Code: int arr[5] = {10, 20, 30, 40, 50};
      int sum = 0;
      for (int i = 0; i < 5; i++) { sum += arr[i]; }

Initial: arr = [10, 20, 30, 40, 50], sum = 0

Iteration 1: i = 0 โ†’ sum = 0 + arr[0] = 0 + 10 = 10
Iteration 2: i = 1 โ†’ sum = 10 + arr[1] = 10 + 20 = 30
Iteration 3: i = 2 โ†’ sum = 30 + arr[2] = 30 + 30 = 60
Iteration 4: i = 3 โ†’ sum = 60 + arr[3] = 60 + 40 = 100
Iteration 5: i = 4 โ†’ sum = 100 + arr[4] = 100 + 50 = 150

Final: sum = 150
// 2. Find maximum
int max = arr[0];
for (int i = 1; i < 5; i++) {
    if (arr[i] > max) {
        max = arr[i];
    }
}
cout << "Max: " << max;  // 50

// 3. Find minimum
int min = arr[0];
for (int i = 1; i < 5; i++) {
    if (arr[i] < min) {
        min = arr[i];
    }
}
cout << "Min: " << min;  // 10

// 4. Count even numbers
int count = 0;
for (int i = 0; i < 5; i++) {
    if (arr[i] % 2 == 0) {
        count++;
    }
}
cout << "Even numbers: " << count;  // 5

// 5. Search for element
int target = 30;
bool found = false;
for (int i = 0; i < 5; i++) {
    if (arr[i] == target) {
        found = true;
        cout << "Found at index " << i;
        break;
    }
}

// 6. Reverse array
int n = 5;
for (int i = 0; i < n/2; i++) {
    int temp = arr[i];
    arr[i] = arr[n-1-i];
    arr[n-1-i] = temp;
}
// Result: {50, 40, 30, 20, 10}

๐Ÿ” Dry Run: Reverse Array

Code: int arr[5] = {10, 20, 30, 40, 50}; int n = 5;
      for (int i = 0; i < n/2; i++) {
          int temp = arr[i];
          arr[i] = arr[n-1-i];
          arr[n-1-i] = temp;
      }

Initial: arr = [10, 20, 30, 40, 50], n = 5, n/2 = 2

Iteration 1 (i=0):
  temp = arr[0] = 10
  arr[0] = arr[4] = 50
  arr[4] = temp = 10
  Array: [50, 20, 30, 40, 10]

Iteration 2 (i=1):
  temp = arr[1] = 20
  arr[1] = arr[3] = 40
  arr[3] = temp = 20
  Array: [50, 40, 30, 20, 10]

Iteration 3: i = 2, but 2 < 2? NO โ†’ Loop exits

Final: arr = [50, 40, 30, 20, 10]

๐ŸŽฏ Dynamic Size:

int arr[] = {10, 20, 30, 40, 50};
int size = sizeof(arr) / sizeof(arr[0]);  // Calculate size

// Now works for any size!
for (int i = 0; i < size; i++) {
    cout << arr[i] << " ";
}
int scores[5] = {85, 90, 78, 92, 88};

cout << "Student Scores:\n";
for (int i = 0; i < 5; i++) {
    cout << "Student " << (i+1) << ": " << scores[i] << endl;
}

Output:


โš ๏ธ Common Mistakes:

int arr[5] = {1, 2, 3, 4, 5};

// โŒ WRONG: Off-by-one error
for (int i = 0; i <= 5; i++) {  // Should be i < 5
    cout << arr[i];  // arr[5] is out of bounds!
}

// โŒ WRONG: Starting at 1
for (int i = 1; i < 5; i++) {  // Misses arr[0]
    cout << arr[i];
}

// โœ… CORRECT
for (int i = 0; i < 5; i++) {
    cout << arr[i];
}

26. Taking Input in Arrays ๐Ÿ“ฅ

Reading values from the user into an array.

๐Ÿ“ Basic Input:

int arr[5];

// Take input for all elements
for (int i = 0; i < 5; i++) {
    cout << "Enter element " << (i+1) << ": ";
    cin >> arr[i];
}

// User enters: 10 20 30 40 50
// Array becomes: {10, 20, 30, 40, 50}

๐Ÿ’ก Complete Example:

#include <iostream>
using namespace std;

int main() {
    int n;
    cout << "How many numbers? ";
    cin >> n;

    int arr[n];  // Variable-sized array

    // Input
    cout << "Enter " << n << " numbers:\n";
    for (int i = 0; i < n; i++) {
        cin >> arr[i];
    }

    // Output
    cout << "You entered: ";
    for (int i = 0; i < n; i++) {
        cout << arr[i] << " ";
    }

    return 0;
}

๐ŸŽฏ Different Input Scenarios:

// Scenario 1: Input with validation
int arr[5];
for (int i = 0; i < 5; i++) {
    cout << "Enter a positive number: ";
    cin >> arr[i];

    while (arr[i] < 0) {
        cout << "Invalid! Enter positive number: ";
        cin >> arr[i];
    }
}

// Scenario 2: Input until sentinel
int arr[100];
int count = 0;

cout << "Enter numbers (-1 to stop):\n";
int num;
while (cin >> num && num != -1) {
    arr[count] = num;
    count++;
}

// Scenario 3: Input student scores
int scores[5];
cout << "Enter scores for 5 students:\n";
for (int i = 0; i < 5; i++) {
    cout << "Student " << (i+1) << ": ";
    cin >> scores[i];
}

๐Ÿ“Š Input and Process:

int n;
cout << "Enter size: ";
cin >> n;

int arr[n];

// Input
cout << "Enter " << n << " numbers:\n";
for (int i = 0; i < n; i++) {
    cin >> arr[i];
}

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

// Calculate average
float average = (float)sum / n;

cout << "Sum: " << sum << endl;
cout << "Average: " << average << endl;

๐ŸŒŸ Multiple Inputs at Once:

int arr[5];

cout << "Enter 5 numbers (space-separated): ";
for (int i = 0; i < 5; i++) {
    cin >> arr[i];  // User enters: 10 20 30 40 50
}
// All at once or one by one - both work!

๐Ÿ’ก Character Array Input:

char letters[5];

cout << "Enter 5 letters:\n";
for (int i = 0; i < 5; i++) {
    cin >> letters[i];
}

// Display
cout << "You entered: ";
for (int i = 0; i < 5; i++) {
    cout << letters[i] << " ";
}

โšก Quick Tip:

Always tell the user how many values to enter and what type of values you expect!


27. Arrays Memory Allocation ๐Ÿ’พ

Arrays are stored in contiguous memory (side by side).

๐Ÿง  Memory Layout:

int arr[5] = {10, 20, 30, 40, 50};
Memory Address:  1000  1004  1008  1012  1016
Value:            10    20    30    40    50
Index:            0     1     2     3     4
                 arr   arr   arr   arr   arr
                 [0]   [1]   [2]   [3]   [4]

๐Ÿ“ Size Calculation:

int arr[5];

// Each int = 4 bytes
// Total = 5 * 4 = 20 bytes

sizeof(arr);        // 20 bytes
sizeof(arr[0]);     // 4 bytes (one element)

// Number of elements
int size = sizeof(arr) / sizeof(arr[0]);  // 20/4 = 5

๐Ÿ“Š Memory by Data Type:

Type Size per Element 5 Elements
char 1 byte 5 bytes
int 4 bytes 20 bytes
float 4 bytes 20 bytes
double 8 bytes 40 bytes

๐ŸŽฏ Contiguous = Fast Access:

// Array elements are neighbors in memory
int arr[5] = {10, 20, 30, 40, 50};

// Fast access by index
arr[0];  // Go to starting address
arr[3];  // Starting address + (3 * 4) bytes

๐ŸŒณ Stack vs Heap:

// STACK (automatic, fast, limited size)
int arr[5];  // Created on stack
// Destroyed automatically when out of scope

// HEAP (manual, slower, large size)
int* arr = new int[1000];  // Created on heap
// Must delete manually!
delete[] arr;

๐Ÿ’ก Why Contiguous Matters:

โœ… Advantages:
- Fast access by index
- CPU cache-friendly
- Predictable memory layout

โŒ Disadvantages:
- Fixed size (can't grow/shrink)
- Must be allocated all at once
- Insertion/deletion in middle is slow

๐Ÿ” Memory Address Example:

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

// Print memory addresses
for (int i = 0; i < 5; i++) {
    cout << "arr[" << i << "] at address: " << &arr[i] << endl;
}

// Output (example):
// arr[0] at address: 0x7ffd5e3
// arr[1] at address: 0x7ffd5e7 (4 bytes apart)
// arr[2] at address: 0x7ffd5eb (4 bytes apart)
// arr[3] at address: 0x7ffd5ef (4 bytes apart)
// arr[4] at address: 0x7ffd5f3 (4 bytes apart)

๐Ÿงฉ Visual Representation:

Stack Memory:
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚   main() local vars โ”‚
โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค
โ”‚   arr[0] = 10       โ”‚ โ† Contiguous
โ”‚   arr[1] = 20       โ”‚ โ† block
โ”‚   arr[2] = 30       โ”‚ โ† of
โ”‚   arr[3] = 40       โ”‚ โ† memory
โ”‚   arr[4] = 50       โ”‚
โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค
โ”‚   other vars        โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

28. Caveats in C++ Arrays โš ๏ธ

Important warnings and limitations of C++ arrays.

๐Ÿšจ 1. No Bounds Checking

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

cout << arr[5];   // โŒ OUT OF BOUNDS! Undefined behavior
cout << arr[10];  // โŒ DANGER! May crash or show garbage
cout << arr[-1];  // โŒ DANGER! Negative index!

// C++ doesn't stop you - YOUR responsibility!

๐Ÿšจ 2. Array Decay (Arrays as Pointers)

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

// In function, array "decays" to pointer
void printArray(int arr[]) {
    // sizeof(arr) won't work here!
    // It returns pointer size, not array size
}

// Must pass size separately
void printArray(int arr[], int size) {
    for (int i = 0; i < size; i++) {
        cout << arr[i];
    }
}

๐Ÿšจ 3. Can't Copy Arrays Directly

int arr1[5] = {1, 2, 3, 4, 5};
int arr2[5];

arr2 = arr1;  // โŒ ERROR! Can't assign arrays

// Must copy element by element
for (int i = 0; i < 5; i++) {
    arr2[i] = arr1[i];  // โœ… Correct
}

๐Ÿšจ 4. Can't Compare Arrays Directly

int arr1[5] = {1, 2, 3, 4, 5};
int arr2[5] = {1, 2, 3, 4, 5};

if (arr1 == arr2) {  // โŒ Compares addresses, not content!
    cout << "Equal";
}

// Must compare element by element
bool equal = true;
for (int i = 0; i < 5; i++) {
    if (arr1[i] != arr2[i]) {
        equal = false;
        break;
    }
}

๐Ÿšจ 5. Can't Return Array from Function

// โŒ WRONG! Can't return array
int[] createArray() {
    int arr[5] = {1, 2, 3, 4, 5};
    return arr;  // ERROR!
}

// โœ… Solution 1: Use pointer (advanced)
int* createArray() {
    int* arr = new int[5];
    return arr;
}

// โœ… Solution 2: Use vector (better)
vector<int> createArray() {
    vector<int> arr = {1, 2, 3, 4, 5};
    return arr;
}

๐Ÿšจ 6. Size Must Be Known at Compile Time

int n;
cin >> n;
int arr[n];  // โš ๏ธ Works in some compilers, not standard C++

// Better: Use vector
vector<int> arr(n);  // โœ… Dynamic size

๐Ÿšจ 7. No Built-in Size Information

int arr[5] = {1, 2, 3, 4, 5};

// โŒ No arr.length() or arr.size()

// Must calculate manually
int size = sizeof(arr) / sizeof(arr[0]);  // Works

// Or pass size as parameter
void process(int arr[], int size) {
    // Use size
}

๐Ÿ“Š Arrays vs Vectors (Better Alternative):

Arrays Vectors
int arr[5] vector<int> arr(5)
Fixed size Dynamic size
No bounds checking Can check bounds
Can't be returned Can be returned
sizeof(arr) arr.size()
No methods Many useful methods
Faster (slight) Safer & easier

๐Ÿ’ก Best Practices:

// โœ… Always check bounds manually
for (int i = 0; i < size; i++) {  // i < size, not i <= size
    arr[i] = value;
}

// โœ… Pass size with array
void func(int arr[], int size) { }

// โœ… Use constants for size
const int SIZE = 5;
int arr[SIZE];

// โœ… Consider using vector instead
#include <vector>
vector<int> arr = {1, 2, 3, 4, 5};

29. Quiz: Arrays Theory โ“

Test your understanding!

Question 1: Array Indexing

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

Q: What is the output?

Answer **30** Explanation: Arrays are 0-indexed, so arr[2] is the 3rd element. - arr[0] = 10 - arr[1] = 20 - arr[2] = 30 โœ…

Question 2: Array Size

int arr[] = {5, 10, 15, 20, 25, 30};
int size = sizeof(arr) / sizeof(arr[0]);

Q: What is the value of size?

Answer **6** Explanation: - sizeof(arr) = 24 bytes (6 elements ร— 4 bytes each) - sizeof(arr[0]) = 4 bytes (one int) - size = 24 / 4 = 6

Question 3: Out of Bounds

int arr[3] = {1, 2, 3};
cout << arr[3];

Q: What happens?

Answer **Undefined behavior (DANGER!)** Explanation: arr[3] is out of bounds. Valid indices are 0, 1, 2. This may crash, show garbage, or appear to work - all are dangerous!

Question 4: Partial Initialization

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

Q: What are the values in the array?

Answer **{10, 20, 0, 0, 0}** Explanation: Uninitialized elements are set to 0.

Question 5: Loop Output

int arr[4] = {2, 4, 6, 8};
for (int i = 0; i < 4; i++) {
    arr[i] = arr[i] * 2;
}

Q: What is the final array?

Answer **{4, 8, 12, 16}** Explanation: Each element is doubled.

Question 6: Array Sum

int arr[5] = {1, 2, 3, 4, 5};
int sum = 0;
for (int i = 0; i < 5; i++) {
    sum += arr[i];
}

Q: What is the value of sum?

Answer **15** Explanation: 1 + 2 + 3 + 4 + 5 = 15

Question 7: First vs Last

int arr[10] = {5, 10, 15, 20, 25, 30, 35, 40, 45, 50};

Q: How to access the last element?

Answer **arr[9]** or **arr[size-1]** Explanation: Size is 10, so last index is 9 (0-based indexing).

Question 8: Character Array

char vowels[5] = {'a', 'e', 'i', 'o', 'u'};
cout << vowels[2];

Q: What is the output?

Answer **i** Explanation: vowels[2] is the 3rd character, which is 'i'.

๐ŸŽฏ Key Takeaways:


30. Ranged For Loops ๐Ÿ”„

Ranged for loops (for-each loops) simplify iterating through arrays.

๐Ÿ“ Syntax:

for (dataType variable : array) {
    // Use variable
}

๐Ÿ’ก Examples:

// Example 1: Simple iteration
int arr[5] = {10, 20, 30, 40, 50};

// Old way (regular for loop)
for (int i = 0; i < 5; i++) {
    cout << arr[i] << " ";
}

// New way (ranged for loop)
for (int num : arr) {
    cout << num << " ";
}

Output:

10 20 30 40 50
char letters[] = {'a', 'b', 'c', 'd'};
for (char ch : letters) {
cout << ch << " ";
}
a b c d
int numbers[] = {1, 2, 3, 4, 5};
int sum = 0;
for (int num : numbers) {
sum += num;
}
cout << "Sum: " << sum;   15

๐Ÿ”„ Regular vs Ranged:

int arr[4] = {5, 10, 15, 20};

// Regular for loop
for (int i = 0; i < 4; i++) {
    cout << arr[i] << " ";
}

// Ranged for loop (cleaner!)
for (int num : arr) {
    cout << num << " ";
}
// Both output: 5 10 15 20

๐Ÿ“Š Comparison:

Regular For Ranged For
for (int i=0; i<n; i++) for (int x : arr)
Need index No index needed
More code Less code
Can modify array Read-only by default
Need to know size Auto-detects size

๐Ÿ”ง Modifying Elements:

int arr[5] = {1, 2, 3, 4, 5};

// โŒ Doesn't modify original (copy)
for (int num : arr) {
    num = num * 2;  // Changes copy, not original
}
// arr still {1, 2, 3, 4, 5}

// โœ… Modifies original (reference)
for (int &num : arr) {  // & means reference
    num = num * 2;
}
// arr now {2, 4, 6, 8, 10}

๐Ÿ’ก Real-World Examples:

// Example 1: Find maximum
int numbers[] = {45, 23, 67, 12, 89, 34};
int max = numbers[0];

for (int num : numbers) {
    if (num > max) {
        max = num;
    }
}
cout << "Max: " << max;  // 89

// Example 2: Count even numbers
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int count = 0;

for (int num : arr) {
    if (num % 2 == 0) {
        count++;
    }
}
cout << "Even numbers: " << count;  // 5

// Example 3: Print with formatting
string names[] = {"Alice", "Bob", "Charlie"};

for (string name : names) {
    cout << "Hello, " << name << "!" << endl;
}
// Hello, Alice!
// Hello, Bob!
// Hello, Charlie!

๐ŸŽฏ When to Use Ranged For:

โšก Best Practice:

// For reading only (use const &)
for (const int &num : arr) {
    cout << num;
}

// For modifying (use &)
for (int &num : arr) {
    num *= 2;
}

// For simple types (can use copy)
for (int num : arr) {
    cout << num;
}

31. Arrays and Functions ๐Ÿ”—

How arrays interact with functions.

๐Ÿ“ Basic Syntax:

// Function that takes an array
void functionName(int arr[], int size) {
    // Use arr and size
}

๐Ÿ’ก Simple Example:

// Function to print array
void printArray(int arr[], int size) {
    for (int i = 0; i < size; i++) {
        cout << arr[i] << " ";
    }
}

int main() {
    int numbers[5] = {10, 20, 30, 40, 50};
    printArray(numbers, 5);  // Pass array and size
    return 0;
}

Output:

10 20 30 40 50

๐Ÿ”„ Passing Arrays:

// Arrays are ALWAYS passed by reference
void modifyArray(int arr[], int size) {
    arr[0] = 999;  // Changes the original!
}

int main() {
    int numbers[3] = {1, 2, 3};
    modifyArray(numbers, 3);

    cout << numbers[0];  // 999 (changed!)
}

โš ๏ธ Important: Arrays Don't Know Their Size

// โŒ WRONG: sizeof doesn't work in functions
void printArray(int arr[]) {
    int size = sizeof(arr) / sizeof(arr[0]);  // WRONG!
    // arr is a pointer here, not an array
}

// โœ… CORRECT: Pass size as parameter
void printArray(int arr[], int size) {
    for (int i = 0; i < size; i++) {
        cout << arr[i] << " ";
    }
}

๐Ÿ“Š Common Array Functions:

// 1. Sum of array
int sumArray(int arr[], int size) {
    int sum = 0;
    for (int i = 0; i < size; i++) {
        sum += arr[i];
    }
    return sum;
}

// 2. Find maximum
int findMax(int arr[], int size) {
    int max = arr[0];
    for (int i = 1; i < size; i++) {
        if (arr[i] > max) {
            max = arr[i];
        }
    }
    return max;
}

// 3. Search element
bool search(int arr[], int size, int target) {
    for (int i = 0; i < size; i++) {
        if (arr[i] == target) {
            return true;
        }
    }
    return false;
}

// 4. Reverse array
void reverseArray(int arr[], int size) {
    for (int i = 0; i < size/2; i++) {
        int temp = arr[i];
        arr[i] = arr[size-1-i];
        arr[size-1-i] = temp;
    }
}

// Using these functions:
int main() {
    int numbers[] = {10, 20, 30, 40, 50};
    int size = 5;

    cout << "Sum: " << sumArray(numbers, size);        // 150
    cout << "Max: " << findMax(numbers, size);         // 50
    cout << "Found: " << search(numbers, size, 30);    // 1 (true)

    reverseArray(numbers, size);
    // numbers is now {50, 40, 30, 20, 10}
}

๐ŸŽฏ Multiple Arrays:

// Function with multiple arrays
void mergeArrays(int arr1[], int size1, int arr2[], int size2, int result[]) {
    int i = 0;

    // Copy first array
    for (int j = 0; j < size1; j++) {
        result[i++] = arr1[j];
    }

    // Copy second array
    for (int j = 0; j < size2; j++) {
        result[i++] = arr2[j];
    }
}

int main() {
    int a[] = {1, 2, 3};
    int b[] = {4, 5, 6};
    int c[6];  // Size = 3 + 3

    mergeArrays(a, 3, b, 3, c);
    // c is now {1, 2, 3, 4, 5, 6}
}

๐Ÿ’ก Return Array Alternative:

// Can't return array directly, but can modify parameter
void createArray(int arr[], int size) {
    for (int i = 0; i < size; i++) {
        arr[i] = i * 10;
    }
}

int main() {
    int numbers[5];
    createArray(numbers, 5);
    // numbers is now {0, 10, 20, 30, 40}
}

32. Passing Array in Functions ๐Ÿ“ค

Deep dive into how arrays are passed to functions.

๐Ÿ”‘ Key Concept: Pass by Reference

// Arrays are AUTOMATICALLY passed by reference
void changeArray(int arr[]) {
    arr[0] = 100;  // Modifies the ORIGINAL array
}

int main() {
    int numbers[3] = {1, 2, 3};
    changeArray(numbers);

    cout << numbers[0];  // 100 (changed!)
}

๐Ÿ†š Arrays vs Regular Variables:

// Regular variable (pass by value)
void changeValue(int x) {
    x = 100;  // Only changes the copy
}

int num = 5;
changeValue(num);
cout << num;  // Still 5 (unchanged)

// Array (pass by reference)
void changeArray(int arr[]) {
    arr[0] = 100;  // Changes the original
}

int numbers[3] = {1, 2, 3};
changeArray(numbers);
cout << numbers[0];  // 100 (changed!)

๐Ÿ“Š Why Pass by Reference?

Reason: Arrays can be HUGE. Copying would be slow and waste memory.

// Imagine an array with 1 million elements
int bigArray[1000000];

// If passed by value (copy):
// - 4 MB of memory copied!
// - Very slow

// Passed by reference:
// - Only address passed (8 bytes)
// - Fast!

๐Ÿ”ข Must Pass Size:

// โœ… Always pass size with array
void printArray(int arr[], int size) {
    for (int i = 0; i < size; i++) {
        cout << arr[i] << " ";
    }
}

// โœ… Alternative: Pass as reference with size
void printArray(int (&arr)[5]) {
    // Now knows size is 5
    for (int i = 0; i < 5; i++) {
        cout << arr[i] << " ";
    }
}

// โŒ WRONG: No size information
void printArray(int arr[]) {
    // How many elements? Don't know!
}

๐Ÿ’ก Different Ways to Declare:

// All these are SAME:
void func1(int arr[]) { }
void func2(int arr[10]) { }  // 10 is ignored!
void func3(int* arr) { }     // Array = pointer

๐Ÿ›ก๏ธ Const Arrays (Protection):

// Prevent function from modifying array
void printArray(const int arr[], int size) {
    for (int i = 0; i < size; i++) {
        cout << arr[i];
    }
    // arr[i] = 10;  // โŒ ERROR! Can't modify const
}

// Use const when function only reads

๐Ÿ“‹ Complete Example:

#include <iostream>
using namespace std;

// Function declarations
void inputArray(int arr[], int size);
void printArray(int arr[], int size);
int sumArray(int arr[], int size);
void doubleArray(int arr[], int size);

int main() {
    int size;
    cout << "Enter size: ";
    cin >> size;

    int arr[size];

    // Input
    inputArray(arr, size);

    // Print
    cout << "Original: ";
    printArray(arr, size);

    // Sum
    cout << "Sum: " << sumArray(arr, size) << endl;

    // Double all elements
    doubleArray(arr, size);
    cout << "Doubled: ";
    printArray(arr, size);

    return 0;
}

void inputArray(int arr[], int size) {
    cout << "Enter " << size << " numbers:\n";
    for (int i = 0; i < size; i++) {
        cin >> arr[i];
    }
}

void printArray(int arr[], int size) {
    for (int i = 0; i < size; i++) {
        cout << arr[i] << " ";
    }
    cout << endl;
}

int sumArray(int arr[], int size) {
    int sum = 0;
    for (int i = 0; i < size; i++) {
        sum += arr[i];
    }
    return sum;
}

void doubleArray(int arr[], int size) {
    for (int i = 0; i < size; i++) {
        arr[i] *= 2;
    }
}

๐ŸŽฏ Key Takeaways:

Point Details
Pass by reference Arrays automatically passed by reference
Must pass size Function can't determine array size
Can modify Changes affect original array
Use const Prevent modifications if only reading
Efficient No copying, just address passing

33. Strings ๐Ÿ“

Strings are sequences of characters used to store text.

๐Ÿ“ Declaration:

#include <string>  // Must include!
using namespace std;

// Method 1: Direct initialization
string name = "John";

// Method 2: Empty string
string message;
message = "Hello";

// Method 3: Copy
string s1 = "Hi";
string s2 = s1;  // s2 is also "Hi"

๐Ÿ’ก Basic Operations:

string text = "Hello";

// Length
cout << text.length();  // 5
cout << text.size();    // 5 (same as length)

// Access characters
cout << text[0];     // 'H' (first char)
cout << text[4];     // 'o' (last char)

// Modify characters
text[0] = 'J';       // "Jello"

// Concatenation (+)
string first = "Hello";
string second = " World";
string full = first + second;  // "Hello World"

// Append
string msg = "Hello";
msg += " World";     // "Hello World"

๐Ÿ”ค String Examples:

// Example 1: User greeting
string name = "Alice";
cout << "Hello, " << name << "!";

Output:

Hello, Alice!
string subject = "C++";
string verb = "is";
string adj = "awesome";
string sentence = subject + " " + verb + " " + adj + "!";
string input;
if (input.empty()) {
cout << "String is empty";
}

๐Ÿ“Š String vs Character:

String Character
string name = "John"; char initial = 'J';
Multiple characters Single character
Double quotes " " Single quotes ' '
Can be empty Always one character
Has methods (.length()) Just a value

๐Ÿ” String Comparison:

string s1 = "apple";
string s2 = "apple";
string s3 = "banana";

// Compare with ==
if (s1 == s2) {
    cout << "Equal";        // โœ… Prints
}

if (s1 == s3) {
    cout << "Equal";        // โŒ Doesn't print
}

// Alphabetical comparison
if (s1 < s3) {
    cout << "s1 comes before s3";  // โœ… apple < banana
}

๐ŸŽฏ Common Use Cases:

// 1. Store names
string firstName = "John";
string lastName = "Doe";
string fullName = firstName + " " + lastName;

// 2. Messages
string errorMsg = "Error: File not found";
string successMsg = "Success!";

// 3. User input (more on this next topic)
string username;
cout << "Enter username: ";
cin >> username;

// 4. Iteration through characters
string word = "Hello";
for (int i = 0; i < word.length(); i++) {
    cout << word[i] << " ";
}

Output:

H e l l o
for (char ch : word) {
cout << ch << " ";
}
H e l l o

๐Ÿ’ก String is Dynamic:

// Unlike arrays, strings can grow!
string text = "Hi";
text += " there";   // "Hi there"
text += "!";        // "Hi there!"
// Size adjusts automatically

34. Taking Input in Strings ๐Ÿ“ฅ

Different ways to read strings from user.

๐Ÿ“ Method 1: cin (Single Word)

string name;
cout << "Enter name: ";
cin >> name;

// User types: John Doe
// name = "John" (stops at space!)

โš ๏ธ Problem: cin stops at whitespace (space, tab, newline).

๐Ÿ“ Method 2: getline (Full Line)

string fullName;
cout << "Enter full name: ";
getline(cin, fullName);

// User types: John Doe
// fullName = "John Doe" โœ… (includes space)

๐Ÿ“Š cin vs getline:

cin getline
cin >> str; getline(cin, str);
Stops at space Reads entire line
Single word only Multiple words
"John" from "John Doe" "John Doe"

๐Ÿ’ก Complete Examples:

// Example 1: Single word
string username;
cout << "Enter username: ";
cin >> username;  // Good for single words

// Example 2: Full sentence
string message;
cout << "Enter message: ";
getline(cin, message);  // Good for sentences

// Example 3: Multiple strings
string first, last;
cout << "Enter first name: ";
cin >> first;
cout << "Enter last name: ";
cin >> last;
string full = first + " " + last;

โš ๏ธ Common Problem: Mixing cin and getline

int age;
string name;

cout << "Enter age: ";
cin >> age;  // Leaves newline in buffer!

cout << "Enter name: ";
getline(cin, name);  // โŒ Reads empty string!

// โœ… FIX: Clear the buffer
cin.ignore();  // Add this line!
getline(cin, name);  // Now works โœ…

๐Ÿ”ง The Complete Fix:

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

int main() {
    int age;
    string name;

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

    cin.ignore();  // Clear newline from buffer

    cout << "Enter full name: ";
    getline(cin, name);

    cout << "Age: " << age << endl;
    cout << "Name: " << name << endl;

    return 0;
}

๐Ÿ“‹ Different Scenarios:

// Scenario 1: Only strings (no problem)
string s1, s2;
getline(cin, s1);
getline(cin, s2);  // Works fine

// Scenario 2: Only cin (no problem)
string s1, s2;
cin >> s1;
cin >> s2;  // Works fine (single words)

// Scenario 3: Mixed (needs fix)
int num;
string text;
cin >> num;
cin.ignore();  // โœ… Must add this!
getline(cin, text);

๐ŸŽฏ When to Use What:

// Use cin for:
// - Single words
// - Numbers followed by words
string username;
cin >> username;  // โœ… Good

// Use getline for:
// - Full names
// - Sentences
// - Any text with spaces
string address;
getline(cin, address);  // โœ… Good

๐Ÿ’ก Reading Multiple Lines:

cout << "Enter 3 sentences:\n";

string line1, line2, line3;
getline(cin, line1);
getline(cin, line2);
getline(cin, line3);

// Or in a loop
string lines[3];
for (int i = 0; i < 3; i++) {
    getline(cin, lines[i]);
}

35. String vs Arrays ๐Ÿ†š

Comparing strings and character arrays.

๐Ÿ“Š Main Differences:

Feature String Character Array
Type string name char name[10]
Size Dynamic (grows/shrinks) Fixed at declaration
Declaration string s = "Hi"; char s[] = {'H','i','\0'};
Easy to use โœ… Yes โŒ More complex
Functions Many (.length(), .substr()) Few
Assignment s1 = s2; โœ… Can't assign directly
Comparison s1 == s2 โœ… Can't compare directly
Concatenation s1 + s2 โœ… Manual copying needed
Null terminator Automatic Must add '\0'

๐Ÿ’ก Examples Side-by-Side:

// STRING (Easy)
string name = "John";
name += " Doe";              // โœ… Simple
cout << name.length();       // โœ… Easy
if (name == "John Doe") {}   // โœ… Works

// CHARACTER ARRAY (Complex)
char name[20] = "John";
strcat(name, " Doe");        // โŒ Need <cstring>
cout << strlen(name);        // โŒ Need <cstring>
if (strcmp(name, "John Doe") == 0) {}  // โŒ Complex

๐Ÿ”ค Character Arrays:

// Declaration
char word[6] = "Hello";  // Needs 6: H e l l o \0
char word[] = "Hello";   // Size auto = 6

// Must end with '\0' (null terminator)
char arr[] = {'H', 'e', 'l', 'l', 'o', '\0'};

// Access
cout << word[0];  // 'H'

// No easy concatenation
char s1[20] = "Hello";
char s2[] = " World";
strcat(s1, s2);  // Complex!

๐ŸŽฏ When to Use What:

Use String (Modern C++):

// โœ… Almost always use string
string name = "John";
string message = "Hello " + name;

// Easy operations
name.length();
name.empty();
name.substr(0, 4);
name.find("oh");

Use Character Arrays (Rare Cases):

// Only when required by:
// - Old C libraries
// - Specific low-level code
// - Memory constraints

char buffer[100];
scanf("%s", buffer);  // Old C-style input

๐Ÿ“‹ Conversion Between Them:

// String to Character Array
string str = "Hello";
char arr[10];
strcpy(arr, str.c_str());  // Convert

// Character Array to String
char arr[] = "Hello";
string str = arr;  // Automatic conversion โœ…

// Or explicit
string str(arr);

๐Ÿ’ก Why Strings Are Better:

// 1. Dynamic Size
string s = "Hi";
s += " there";
s += " friend";  // Grows automatically โœ…

char c[5] = "Hi";
// Can't grow beyond 5 โŒ

// 2. Easy Comparison
string s1 = "apple", s2 = "banana";
if (s1 == s2) {}  // โœ… Simple

char c1[] = "apple", c2[] = "banana";
if (strcmp(c1, c2) == 0) {}  // โŒ Complex

// 3. Easy Concatenation
string s = "Hello" + string(" World");  // โœ…

char c1[20] = "Hello";
char c2[] = " World";
strcat(c1, c2);  // โŒ Need to ensure size

// 4. Methods
string s = "Hello";
s.length();
s.empty();
s.substr(1, 3);
s.find("ll");
s.replace(0, 1, "J");
// So many useful methods! โœ…

๐ŸŽฏ Recommendation:

Always use string unless you have a specific reason not to!

// โœ… Modern C++ (use this!)
#include <string>
string name = "John";

// โŒ Old C-style (avoid!)
#include <cstring>
char name[50];

36. Basic Functions of String ๐Ÿ› ๏ธ

Useful string methods in C++.

๐Ÿ“ Size & Capacity:

string str = "Hello";

str.length();    // 5 (number of characters)
str.size();      // 5 (same as length)
str.empty();     // false (has characters)

string empty = "";
empty.empty();   // true

๐Ÿ” Access Characters:

string str = "Hello";

str[0];          // 'H' (no bounds checking)
str.at(0);       // 'H' (with bounds checking - safer)
str.front();     // 'H' (first character)
str.back();      // 'o' (last character)

โž• Modify Strings:

string str = "Hello";

// Append (add to end)
str.append(" World");     // "Hello World"
str += "!";               // "Hello World!"

// Insert
str.insert(5, " Beautiful");  // "Hello Beautiful World!"
//         ^ position 5

// Erase
str.erase(5, 10);        // Remove 10 chars from position 5

// Replace
str.replace(0, 5, "Hi"); // Replace first 5 chars with "Hi"

// Clear (empty the string)
str.clear();             // ""

โœ‚๏ธ Substrings:

string str = "Hello World";

// Get substring
str.substr(0, 5);        // "Hello" (from 0, length 5)
str.substr(6);           // "World" (from 6 to end)
str.substr(6, 3);        // "Wor" (from 6, length 3)
string str = "Hello World";

// Find substring
size_t pos = str.find("World");     // 6 (position)
pos = str.find("xyz");              // string::npos (not found)

// Check if found
if (str.find("World") != string::npos) {
    cout << "Found!";
}

// Find character
pos = str.find('o');                // 4 (first 'o')

// Find last occurrence
pos = str.rfind('o');               // 7 (last 'o')

๐Ÿ”„ Compare:

string s1 = "apple";
string s2 = "banana";

// Using ==, !=, <, >, <=, >=
if (s1 == s2) {}        // false
if (s1 != s2) {}        // true
if (s1 < s2) {}         // true (alphabetically)

// Using compare()
s1.compare(s2);         // < 0 (s1 < s2)
s1.compare("apple");    // 0 (equal)

๐Ÿ“Š Method Reference Table:

Method What It Does Example
.length() Get size str.length() โ†’ 5
.empty() Check if empty str.empty() โ†’ false
.at(i) Get char at i str.at(0) โ†’ 'H'
.append(s) Add to end str.append("!")
.insert(i, s) Insert at i str.insert(0, "Hi")
.erase(i, n) Remove n chars str.erase(0, 2)
.substr(i, n) Get substring str.substr(0, 3)
.find(s) Find position str.find("lo") โ†’ 3
.replace(i,n,s) Replace chars str.replace(0,2,"X")
.clear() Empty string str.clear()

๐Ÿ’ก Practical Examples:

// Example 1: Email validation
string email = "user@example.com";
if (email.find('@') != string::npos) {
    cout << "Valid email format";
}

// Example 2: Extract filename
string path = "C:/Users/Documents/file.txt";
size_t pos = path.rfind('/');
string filename = path.substr(pos + 1);  // "file.txt"

// Example 3: Count occurrences
string text = "hello world, hello everyone";
string word = "hello";
int count = 0;
size_t pos = 0;

while ((pos = text.find(word, pos)) != string::npos) {
    count++;
    pos += word.length();
}
cout << "Found " << count << " times";  // 2

// Example 4: Remove spaces
string str = "H e l l o";
str.erase(remove(str.begin(), str.end(), ' '), str.end());
// "Hello"

// Example 5: Convert to uppercase
string str = "hello";
for (char &c : str) {
    c = toupper(c);
}
// "HELLO"

// Example 6: Check if string starts with
string str = "Hello World";
string prefix = "Hello";
if (str.substr(0, prefix.length()) == prefix) {
    cout << "Starts with Hello";
}

๐ŸŽฏ Character Functions:

#include <cctype>

char ch = 'a';

// Check type
isalpha(ch);     // true (is letter)
isdigit(ch);     // false (is digit)
isspace(ch);     // false (is whitespace)
islower(ch);     // true (is lowercase)
isupper(ch);     // false (is uppercase)

// Convert
toupper(ch);     // 'A'
tolower('B');    // 'b'

// Use with strings
string str = "Hello";
for (int i = 0; i < str.length(); i++) {
    str[i] = toupper(str[i]);
}
// "HELLO"

37. Vector Basics ๐Ÿ“ฆ

Vectors are dynamic arrays that can grow and shrink in size.

๐ŸŽฏ What is a Vector?

Think of a vector as a smart array that can change size automatically.

Array:   [1][2][3]     โ† Fixed size
Vector:  [1][2][3]...  โ† Can grow!

๐Ÿ“ Declaration:

#include <vector>
using namespace std;

// Method 1: Empty vector
vector<int> numbers;

// Method 2: With size
vector<int> numbers(5);  // 5 elements, all 0

// Method 3: With size and default value
vector<int> numbers(5, 10);  // 5 elements, all 10

// Method 4: With values
vector<int> numbers = {1, 2, 3, 4, 5};

// Other types
vector<float> prices = {9.99, 19.99, 29.99};
vector<string> names = {"Alice", "Bob", "Charlie"};
vector<char> letters = {'a', 'b', 'c'};

๐Ÿ”ข Access Elements:

vector<int> nums = {10, 20, 30, 40, 50};

// Using []
nums[0];        // 10
nums[2];        // 30

// Using .at() (safer - checks bounds)
nums.at(0);     // 10
nums.at(10);    // ERROR! Out of bounds

// Front and back
nums.front();   // 10 (first element)
nums.back();    // 50 (last element)

๐Ÿ“Š Vector vs Array:

Array Vector
int arr[5] vector<int> v(5)
Fixed size Dynamic size
arr[0] v[0] or v.at(0)
No size info v.size()
No methods Many methods
Faster (slight) More flexible

๐Ÿ’ก Why Vectors Are Better:

// Array (fixed)
int arr[5];
// Can't add 6th element!

// Vector (dynamic)
vector<int> vec;
vec.push_back(10);  // Add element
vec.push_back(20);  // Add another
vec.push_back(30);  // Keep adding!
// Size grows automatically โœ…

๐ŸŽฏ Basic Operations:

vector<int> nums;

// Add elements
nums.push_back(10);    // [10]
nums.push_back(20);    // [10, 20]
nums.push_back(30);    // [10, 20, 30]

// Size
cout << nums.size();   // 3

// Check if empty
if (nums.empty()) {
    cout << "Empty";
} else {
    cout << "Has elements";  // This prints
}

// Remove last element
nums.pop_back();       // [10, 20]

// Clear all
nums.clear();          // []
cout << nums.size();   // 0

๐Ÿ”„ Iterating:

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

// Method 1: Regular for loop
for (int i = 0; i < nums.size(); i++) {
    cout << nums[i] << " ";
}

// Method 2: Ranged for loop (best!)
for (int num : nums) {
    cout << num << " ";
}

// Method 3: Iterator
for (auto it = nums.begin(); it != nums.end(); it++) {
    cout << *it << " ";
}

๐Ÿ’ก Practical Example:

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

int main() {
    vector<int> scores;

    // Input scores
    cout << "Enter scores (-1 to stop):\n";
    int score;
    while (cin >> score && score != -1) {
        scores.push_back(score);
    }

    // Calculate average
    int sum = 0;
    for (int s : scores) {
        sum += s;
    }
    double avg = (double)sum / scores.size();

    cout << "Average: " << avg << endl;

    return 0;
}

๐ŸŽฏ When to Use Vector:

โœ… Use Vector when:
- Size changes during runtime
- Need to add/remove elements
- Want safety and convenience
- Building dynamic data structures

โŒ Use Array when:
- Size is known and fixed
- Need maximum performance (rare)
- Working with low-level code


38. Vector Implementation - 1 ๐Ÿ”ง

Common vector operations and methods.

โž• Adding Elements:

vector<int> nums;

// push_back (add to end)
nums.push_back(10);    // [10]
nums.push_back(20);    // [10, 20]
nums.push_back(30);    // [10, 20, 30]

// insert (add at position)
nums.insert(nums.begin(), 5);      // [5, 10, 20, 30]
nums.insert(nums.begin() + 2, 15); // [5, 10, 15, 20, 30]
//          ^ position

โž– Removing Elements:

vector<int> nums = {10, 20, 30, 40, 50};

// pop_back (remove last)
nums.pop_back();       // [10, 20, 30, 40]

// erase (remove at position)
nums.erase(nums.begin());          // [20, 30, 40]
nums.erase(nums.begin() + 1);      // [20, 40]

// clear (remove all)
nums.clear();          // []

๐Ÿ“ Size Operations:

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

// Get size
nums.size();           // 5

// Check if empty
nums.empty();          // false

// Resize
nums.resize(3);        // [1, 2, 3]
nums.resize(5);        // [1, 2, 3, 0, 0]
nums.resize(7, 10);    // [1, 2, 3, 0, 0, 10, 10]
//                        ^ new elements filled with 10

๐Ÿ”„ Modify Elements:

vector<int> nums = {10, 20, 30, 40, 50};

// Update element
nums[2] = 100;         // [10, 20, 100, 40, 50]

// Update with at()
nums.at(0) = 5;        // [5, 20, 100, 40, 50]

// Swap two vectors
vector<int> v1 = {1, 2, 3};
vector<int> v2 = {4, 5, 6};
v1.swap(v2);
// v1 is now {4, 5, 6}
// v2 is now {1, 2, 3}

๐Ÿ“Š Method Reference:

Method What It Does Example
.push_back(x) Add to end v.push_back(5)
.pop_back() Remove last v.pop_back()
.insert(pos, x) Insert at position v.insert(v.begin(), 5)
.erase(pos) Remove at position v.erase(v.begin())
.size() Get size v.size() โ†’ 5
.empty() Check if empty v.empty() โ†’ false
.clear() Remove all v.clear()
.resize(n) Change size v.resize(10)
.front() First element v.front() โ†’ 10
.back() Last element v.back() โ†’ 50

๐Ÿ’ก Practical Examples:

// Example 1: Dynamic input
vector<int> numbers;
int n;
cout << "How many numbers? ";
cin >> n;

for (int i = 0; i < n; i++) {
    int num;
    cin >> num;
    numbers.push_back(num);
}

// Example 2: Remove all even numbers
vector<int> nums = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

for (int i = 0; i < nums.size(); i++) {
    if (nums[i] % 2 == 0) {
        nums.erase(nums.begin() + i);
        i--;  // Adjust index after removal
    }
}
// Result: {1, 3, 5, 7, 9}

// Example 3: Insert sorted
vector<int> sorted = {1, 3, 5, 7, 9};
int value = 6;

for (int i = 0; i < sorted.size(); i++) {
    if (value < sorted[i]) {
        sorted.insert(sorted.begin() + i, value);
        break;
    }
}
// Result: {1, 3, 5, 6, 7, 9}

// Example 4: Stack operations (LIFO)
vector<int> stack;

// Push
stack.push_back(10);  // Push 10
stack.push_back(20);  // Push 20
stack.push_back(30);  // Push 30

// Pop
stack.pop_back();     // Remove 30
stack.pop_back();     // Remove 20

// Top
cout << stack.back(); // 10

// Example 5: Queue operations (FIFO)
vector<int> queue;

// Enqueue (add to end)
queue.push_back(10);
queue.push_back(20);
queue.push_back(30);

// Dequeue (remove from front)
queue.erase(queue.begin());  // Remove 10

๐ŸŽฏ Common Patterns:

// Pattern 1: Fill with values
vector<int> v(5, 10);  // [10, 10, 10, 10, 10]

// Pattern 2: Copy vector
vector<int> v1 = {1, 2, 3};
vector<int> v2 = v1;   // Copy

// Pattern 3: Reverse
vector<int> v = {1, 2, 3, 4, 5};
reverse(v.begin(), v.end());  // [5, 4, 3, 2, 1]

// Pattern 4: Sort
vector<int> v = {5, 2, 8, 1, 9};
sort(v.begin(), v.end());     // [1, 2, 5, 8, 9]

39. Vector Implementation - 2 ๐Ÿ”ง

Advanced vector features and performance considerations.

๐Ÿ“ฆ Capacity vs Size:

vector<int> nums;

nums.size();        // 0 (number of elements)
nums.capacity();    // 0 (allocated memory)

nums.push_back(1);
nums.size();        // 1
nums.capacity();    // 1

nums.push_back(2);
nums.size();        // 2
nums.capacity();    // 2

nums.push_back(3);
nums.size();        // 3
nums.capacity();    // 4 (doubled!)

๐Ÿ“Š Size vs Capacity Explained:

Size: How many elements are in use
Capacity: How much space is allocated

[1][2][3][ ][ ]
 โ””โ”€size = 3โ”€โ”˜
 โ””โ”€โ”€capacity = 5โ”€โ”€โ”˜

๐ŸŽฏ Reserve & Shrink:

vector<int> nums;

// Reserve space (optimization)
nums.reserve(100);      // Allocate space for 100 elements
nums.capacity();        // 100
nums.size();            // 0 (still empty)

// Now adding elements is faster (no reallocation)
for (int i = 0; i < 100; i++) {
    nums.push_back(i);  // Fast!
}

// Shrink to fit (free unused memory)
nums.resize(10);        // Keep only 10 elements
nums.shrink_to_fit();   // Free extra memory
nums.capacity();        // 10 (matched to size)

๐Ÿ”„ Iterators:

vector<int> nums = {10, 20, 30, 40, 50};

// begin() and end()
auto start = nums.begin();   // Points to first element
auto finish = nums.end();    // Points AFTER last element

// Using iterators
for (auto it = nums.begin(); it != nums.end(); it++) {
    cout << *it << " ";      // * to get value
}

// Reverse iterators
for (auto it = nums.rbegin(); it != nums.rend(); it++) {
    cout << *it << " ";      // Prints: 50 40 30 20 10
}

๐Ÿ“‹ 2D Vectors (Matrix):

// Create 3x4 matrix (3 rows, 4 columns)
vector<vector<int>> matrix(3, vector<int>(4));

// Initialize with values
vector<vector<int>> matrix = {
    {1, 2, 3, 4},
    {5, 6, 7, 8},
    {9, 10, 11, 12}
};

// Access elements
matrix[0][0];           // 1
matrix[1][2];           // 7
matrix[2][3];           // 12

// Iterate through 2D vector
for (int i = 0; i < matrix.size(); i++) {
    for (int j = 0; j < matrix[i].size(); j++) {
        cout << matrix[i][j] << " ";
    }
    cout << endl;
}

// Ranged for loop (cleaner)
for (auto& row : matrix) {
    for (int val : row) {
        cout << val << " ";
    }
    cout << endl;
}

๐Ÿงฎ Algorithm Functions:

#include <algorithm>

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

// Sort
sort(nums.begin(), nums.end());
// [1, 2, 3, 5, 8, 9]

// Reverse
reverse(nums.begin(), nums.end());
// [9, 8, 5, 3, 2, 1]

// Find
auto it = find(nums.begin(), nums.end(), 5);
if (it != nums.end()) {
    cout << "Found at position: " << (it - nums.begin());
}

// Min/Max element
auto minIt = min_element(nums.begin(), nums.end());
auto maxIt = max_element(nums.begin(), nums.end());
cout << "Min: " << *minIt;
cout << "Max: " << *maxIt;

// Count occurrences
int cnt = count(nums.begin(), nums.end(), 5);

// Sum
int sum = accumulate(nums.begin(), nums.end(), 0);

โšก Performance Tips:

// โœ… GOOD: Reserve if you know size
vector<int> nums;
nums.reserve(1000);         // Allocate once
for (int i = 0; i < 1000; i++) {
    nums.push_back(i);      // No reallocation!
}

// โŒ BAD: Frequent reallocation
vector<int> nums;           // Capacity doubles multiple times
for (int i = 0; i < 1000; i++) {
    nums.push_back(i);      // Slow!
}

// โœ… GOOD: Use emplace_back for objects
vector<string> names;
names.emplace_back("John"); // Constructs in place
names.push_back("Jane");    // Creates then copies

// โœ… GOOD: Pass by reference
void process(const vector<int>& v) {  // No copy
    // Read-only operations
}

// โŒ BAD: Pass by value
void process(vector<int> v) {  // Copies entire vector!
    // Slow for large vectors
}

๐Ÿ’ก Advanced Examples:

// Example 1: Remove duplicates
vector<int> nums = {1, 2, 2, 3, 3, 3, 4, 5, 5};
sort(nums.begin(), nums.end());
nums.erase(unique(nums.begin(), nums.end()), nums.end());
// Result: {1, 2, 3, 4, 5}

// Example 2: Partition (even/odd)
vector<int> nums = {1, 2, 3, 4, 5, 6, 7, 8, 9};
partition(nums.begin(), nums.end(), [](int x) { return x % 2 == 0; });
// Even numbers first, then odd

// Example 3: Custom sort
vector<int> nums = {5, 2, 8, 1, 9};
sort(nums.begin(), nums.end(), greater<int>());
// Descending: {9, 8, 5, 2, 1}

// Example 4: Vector of pairs
vector<pair<string, int>> students = {
    {"Alice", 85},
    {"Bob", 92},
    {"Charlie", 78}
};

// Sort by score
sort(students.begin(), students.end(), 
     [](auto& a, auto& b) { return a.second > b.second; });

40. Quiz: Vectors โ“

Test your vector knowledge!

Question 1: Basic Operations

vector<int> v = {1, 2, 3};
v.push_back(4);
v.pop_back();
v.push_back(5);
cout << v.size();

Q: What is the output?

Answer **4** Explanation: - Start: {1, 2, 3} (size = 3) - push_back(4): {1, 2, 3, 4} (size = 4) - pop_back(): {1, 2, 3} (size = 3) - push_back(5): {1, 2, 3, 5} (size = 4)

Question 2: Size vs Capacity

vector<int> v;
v.reserve(10);
cout << v.size() << " " << v.capacity();

Q: What is the output?

Answer **0 10** Explanation: - size() = 0 (no elements added yet) - capacity() = 10 (space reserved)

Question 3: Access

vector<int> v = {10, 20, 30, 40, 50};
cout << v.front() << " " << v.back();

Q: What is the output?

Answer **10 50** Explanation: - front() returns first element (10) - back() returns last element (50)

Question 4: Insertion

vector<int> v = {1, 2, 3};
v.insert(v.begin() + 1, 10);

Q: What is the vector after insertion?

Answer **{1, 10, 2, 3}** Explanation: - v.begin() + 1 points to position 1 (second element) - 10 is inserted there

Question 5: Erase

vector<int> v = {10, 20, 30, 40, 50};
v.erase(v.begin() + 2);

Q: What is the vector after erase?

Answer **{10, 20, 40, 50}** Explanation: - v.begin() + 2 points to position 2 (element 30) - 30 is removed

Question 6: Vector vs Array

Q: Which is TRUE about vectors?

A) Fixed size like arrays
B) Can grow and shrink dynamically
C) No built-in methods
D) Faster than arrays always

Answer **B) Can grow and shrink dynamically** Explanation: - Vectors can change size (A is wrong) - Vectors have many methods (C is wrong) - Arrays can be slightly faster (D is wrong)

Question 7: 2D Vector

vector<vector<int>> matrix = {
    {1, 2, 3},
    {4, 5, 6}
};
cout << matrix[1][2];

Q: What is the output?

Answer **6** Explanation: - matrix[1] is second row: {4, 5, 6} - matrix[1][2] is third element: 6

Question 8: Empty Check

vector<int> v;
if (v.empty()) {
    cout << "A";
} else {
    cout << "B";
}

Q: What is the output?

Answer **A** Explanation: - v is empty (no elements) - empty() returns true

๐ŸŽฏ Key Takeaways:


41. Multi-dimensional Arrays ๐ŸŽฒ

Multi-dimensional arrays are arrays of arrays, commonly used for matrices and tables.

๐Ÿ“Š 2D Array (Matrix):

// Declaration: type name[rows][columns]
int matrix[3][4];  // 3 rows, 4 columns

// Visualization:
//      Col0 Col1 Col2 Col3
// Row0 [ ][ ][ ][ ]
// Row1 [ ][ ][ ][ ]
// Row2 [ ][ ][ ][ ]

๐Ÿ“ Initialization:

// Method 1: Direct initialization
int matrix[3][3] = {
    {1, 2, 3},
    {4, 5, 6},
    {7, 8, 9}
};

// Method 2: Without inner braces
int matrix[2][3] = {1, 2, 3, 4, 5, 6};
// Fills row by row

// Method 3: Partial initialization
int matrix[3][3] = {
    {1, 2},      // Rest filled with 0
    {3},         // Rest filled with 0
    {}           // All 0
};

๐Ÿ”ข Accessing Elements:

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

// Access: matrix[row][column]
matrix[0][0];  // 1 (first row, first column)
matrix[0][2];  // 3 (first row, third column)
matrix[1][1];  // 5 (second row, second column)
matrix[2][2];  // 9 (third row, third column)

// Modify
matrix[1][1] = 100;  // Changes 5 to 100

๐Ÿ”„ Iterating Through 2D Array:

int matrix[3][4] = {
    {1, 2, 3, 4},
    {5, 6, 7, 8},
    {9, 10, 11, 12}
};

// Nested loop (row by row)
for (int i = 0; i < 3; i++) {       // Rows
    for (int j = 0; j < 4; j++) {   // Columns
        cout << matrix[i][j] << " ";
    }
    cout << endl;  // New line after each row
}

Output:


๐Ÿ” Dry Run: 2D Array Iteration

Code: int matrix[3][4] = {{1,2,3,4}, {5,6,7,8}, {9,10,11,12}};
      for (int i = 0; i < 3; i++) {
          for (int j = 0; j < 4; j++) {
              cout << matrix[i][j] << " ";
          }
          cout << endl;
      }

Outer Loop - Iteration 1 (i=0):
  Inner Loop:
    j=0: Print matrix[0][0] = 1
    j=1: Print matrix[0][1] = 2
    j=2: Print matrix[0][2] = 3
    j=3: Print matrix[0][3] = 4
  Print newline
  Output so far: "1 2 3 4\n"

Outer Loop - Iteration 2 (i=1):
  Inner Loop:
    j=0: Print matrix[1][0] = 5
    j=1: Print matrix[1][1] = 6
    j=2: Print matrix[1][2] = 7
    j=3: Print matrix[1][3] = 8
  Print newline
  Output so far: "1 2 3 4\n5 6 7 8\n"

Outer Loop - Iteration 3 (i=2):
  Inner Loop:
    j=0: Print matrix[2][0] = 9
    j=1: Print matrix[2][1] = 10
    j=2: Print matrix[2][2] = 11
    j=3: Print matrix[2][3] = 12
  Print newline

Final Output:
1 2 3 4
5 6 7 8
9 10 11 12

๐Ÿ’ก Common Operations:

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

// 1. Input
for (int i = 0; i < 3; i++) {
    for (int j = 0; j < 3; j++) {
        cin >> matrix[i][j];
    }
}

// 2. Sum of all elements
int sum = 0;
for (int i = 0; i < 3; i++) {
    for (int j = 0; j < 3; j++) {
        sum += matrix[i][j];
    }
}

// 3. Find maximum
int max = matrix[0][0];
for (int i = 0; i < 3; i++) {
    for (int j = 0; j < 3; j++) {
        if (matrix[i][j] > max) {
            max = matrix[i][j];
        }
    }
}

// 4. Row sum
for (int i = 0; i < 3; i++) {
    int rowSum = 0;
    for (int j = 0; j < 3; j++) {
        rowSum += matrix[i][j];
    }
    cout << "Row " << i << " sum: " << rowSum << endl;
}

// 5. Column sum
for (int j = 0; j < 3; j++) {
    int colSum = 0;
    for (int i = 0; i < 3; i++) {
        colSum += matrix[i][j];
    }
    cout << "Column " << j << " sum: " << colSum << endl;
}

// 6. Diagonal sum (square matrix)
int diagSum = 0;
for (int i = 0; i < 3; i++) {
    diagSum += matrix[i][i];  // Main diagonal
}

๐Ÿง  Memory Layout (Row-Major Order):

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

// Memory layout (contiguous):
// [1][2][3][4][5][6]
//  โ””โ”€Row 0โ”€โ”˜โ””โ”€Row 1โ”€โ”˜

// Address calculation:
// matrix[i][j] = base_address + (i * columns + j) * sizeof(type)

๐Ÿ“Š Practical Examples:

// Example 1: Tic-Tac-Toe board
char board[3][3] = {
    {'X', 'O', 'X'},
    {'O', 'X', 'O'},
    {'O', 'X', 'X'}
};

// Example 2: Student grades (students x subjects)
int grades[4][3] = {
    {85, 90, 78},  // Student 1
    {92, 88, 95},  // Student 2
    {76, 82, 80},  // Student 3
    {88, 91, 87}   // Student 4
};

// Calculate each student's average
for (int i = 0; i < 4; i++) {
    int sum = 0;
    for (int j = 0; j < 3; j++) {
        sum += grades[i][j];
    }
    cout << "Student " << (i+1) << " average: " 
         << (sum / 3.0) << endl;
}

// Example 3: Matrix transpose
int matrix[3][3] = {
    {1, 2, 3},
    {4, 5, 6},
    {7, 8, 9}
};

int transpose[3][3];
for (int i = 0; i < 3; i++) {
    for (int j = 0; j < 3; j++) {
        transpose[j][i] = matrix[i][j];
    }
}
// Result:
// 1 4 7
// 2 5 8
// 3 6 9

๐ŸŽฏ 3D Arrays (and beyond):

// 3D array: [depth][rows][columns]
int cube[2][3][4];  // 2 layers, 3 rows, 4 columns

// Think of it as:
// Layer 0:
//   [1][2][3][4]
//   [5][6][7][8]
//   [9][10][11][12]
// Layer 1:
//   [13][14][15][16]
//   [17][18][19][20]
//   [21][22][23][24]

// Access
cube[0][1][2];  // Layer 0, Row 1, Column 2

// Iterate
for (int i = 0; i < 2; i++) {      // Layers
    for (int j = 0; j < 3; j++) {  // Rows
        for (int k = 0; k < 4; k++) {  // Columns
            cout << cube[i][j][k] << " ";
        }
    }
}

๐Ÿ†š 2D Array vs 2D Vector:

// 2D Array (fixed size)
int arr[3][4];

// 2D Vector (dynamic)
vector<vector<int>> vec(3, vector<int>(4));

// Vector advantages:
vec.push_back({1, 2, 3, 4});  // Add row
vec[0].push_back(5);          // Add to first row
vec.size();                   // Number of rows
vec[0].size();                // Columns in first row

๐ŸŽ‰ Conclusion

Congratulations! You've completed the C++ Fundamentals guide! ๐Ÿš€

๐Ÿ“š What You've Learned:

โœ… Basics: Variables, Data Types, Operators
โœ… Control Flow: If-Else, Loops, Switch
โœ… Functions: Arguments, Return, Scope
โœ… Arrays: Declaration, Iteration, Memory
โœ… Strings: Operations, Methods, Input
โœ… Vectors: Dynamic Arrays, STL Container
โœ… Multi-dimensional: Matrices and beyond

๐ŸŽฏ Next Steps:

  1. Practice, Practice, Practice!
    - Solve coding problems on platforms like:

    • LeetCode
    • HackerRank
    • Codeforces
    • CodeChef
  2. Learn Object-Oriented Programming (OOP)
    - Classes and Objects
    - Inheritance
    - Polymorphism
    - Encapsulation

  3. Explore Advanced Topics
    - Pointers and References
    - Dynamic Memory
    - STL (Containers, Algorithms)
    - Templates
    - File I/O

  4. Build Projects
    - Calculator
    - To-Do List
    - Game (Tic-Tac-Toe, Snake)
    - Student Management System

๐Ÿ’ก Tips for Success:

๐ŸŒŸ Remember:

"The only way to learn programming is by writing programs."

โ€” Dennis Ritchie (Creator of C)

Keep coding, keep learning, and most importantlyโ€”have fun! ๐ŸŽŠ


๐Ÿ“– Quick Reference Card:

// Variables
int x = 5;
float pi = 3.14;
string name = "John";

// Conditions
if (x > 0) { }
else if (x == 0) { }
else { }

// Loops
for (int i = 0; i < 10; i++) { }
while (condition) { }

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

// Arrays
int arr[5] = {1, 2, 3, 4, 5};
for (int i = 0; i < 5; i++) {
    cout << arr[i];
}

// Vectors
vector<int> v = {1, 2, 3};
v.push_back(4);
v.pop_back();

// Strings
string str = "Hello";
str.length();
str.substr(0, 3);
str.find("ll");

// Input/Output
cin >> x;
cout << x;
getline(cin, str);

Thank you for learning with this guide! ๐Ÿ“šโœจ

Happy Coding! ๐Ÿ’ป๐ŸŽ‰