๐ 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
- What is C++?
- Literals
- Comments
- Variables
- Data Types
- Print Output
- Operators Part 1
- Operators Part 2
- Booleans
- If-Else
- Else-If Ladder
- While Loop
- For Loop
- Loops Standard Problems
- Break and Continue
- Switch Statement
- Functions
- Function Arguments
- Return Statement
- Local Variable
- Why Do We Use Arguments and Return Type?
- Standard Library Functions
- Nested Functions
- Arrays
- Iterating and Updating Arrays
- Taking Input in Arrays
- Arrays Memory Allocation
- Caveats in C++ Arrays
- Quiz: Arrays Theory
- Ranged For Loops
- Arrays and Functions
- Passing Array in Functions
- Strings
- Taking Input in Strings
- String vs Arrays
- Basic Functions of String
- Vector Basics
- Vector Implementation - 1
- Vector Implementation - 2
- Quiz: Vectors
- Multi-dimensional Arrays
1. What is C++? ๐ค
C++ is a powerful programming language that extends C with object-oriented features.
๐ฏ Key Points:
- Created by: Bjarne Stroustrup in 1979
- Type: Compiled language (code โ machine language)
- Use cases: Games, Operating Systems, Browsers, Databases
๐ 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++?
- โก Fast performance - runs close to hardware
- ๐ฎ Game development - Unreal Engine uses C++
- ๐ผ Job opportunities - high demand in tech companies
- ๐ง Strong foundation - makes learning other languages easier
// 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:
- Single quotes
' 'โ One character - Double quotes
" "โ Multiple characters (string)
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:
- โ๏ธ Explain WHY, not WHAT
- ๐ Use comments for complex logic
- ๐ซ Don't comment obvious code
- ๐ Keep comments updated with code
// โ 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:
- โ
Can contain: letters, digits, underscore
_ - โ Must start with: letter or underscore
- โ Cannot use: spaces, special characters, keywords
- โ ๏ธ Case-sensitive:
ageโAgeโAGE
๐จ Naming Conventions:
// Good names (descriptive)
int studentAge;
float accountBalance;
string userName;
// Bad names (unclear)
int x;
float f;
string s;
๐ก Quick Tips:
- Use camelCase for variable names:
myVariableName - Use meaningful names:
totalPriceinstead oftp
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:
๐ก 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:
true= 1 (any non-zero value)false= 0- Used in conditions (if, while, for)
- Result of comparison operations
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:
๐ก 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:
- โ When you have two choices (yes/no situations)
- โ Simple true/false decisions
- โ Either/or scenarios
โก 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:
๐ก 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:
- โ ๏ธ Conditions are checked top to bottom
- โ ๏ธ Only ONE block executes (the first true one)
- โ ๏ธ Once a condition is true, rest are skipped
- โ
elseis optional (catches everything else)
๐ก 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:
๐ก 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:
- โ When you don't know how many times to loop
- โ Input validation (keep asking until correct)
- โ Menu-driven programs
- โ Game loops (until game over)
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:
๐ก 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:
CONTINUE:
๐ก 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:
- โ Multiple exact values to check
- โ Menu-driven programs
- โ Fixed set of options
- โ Don't use for ranges (
x > 10)
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:
๐ฏ 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:
- โ Return type must match function type
- โ
Code after
returnwon't run - โ Every path should have a return (except void)
// โ 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:
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:
- โ Keep variables as local as possible
- โ Declare variables close to where used
- โ Minimize global variables (hard to track)
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:
๐ก 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:
- โ Index starts at 0 (not 1!)
- โ Size is fixed after declaration
- โ All elements same type
- โ ๏ธ No automatic bounds checking (can access invalid index)
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] << " ";
}
๐ก Print with Formatting:
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 = 6Question 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 = 15Question 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:
- โ Arrays start at index 0
- โ Last index is size - 1
- โ Use sizeof(arr) / sizeof(arr[0]) for size
- โ ๏ธ No automatic bounds checking
- โ ๏ธ Uninitialized elements = 0
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:
- โ Reading all elements
- โ Don't need index
- โ Simpler, cleaner code
- โ Don't use if you need index
- โ Don't use if skipping elements
โก 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)
๐ Search:
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 thereQuestion 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 removedQuestion 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: 6Question 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:
- โ Vectors are dynamic (can grow/shrink)
- โ size() = elements count, capacity() = allocated space
- โ front() = first, back() = last
- โ Use push_back() to add, pop_back() to remove
- โ reserve() to pre-allocate space
- โ Vectors are better than arrays in most cases
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:
-
Practice, Practice, Practice!
- Solve coding problems on platforms like:- LeetCode
- HackerRank
- Codeforces
- CodeChef
-
Learn Object-Oriented Programming (OOP)
- Classes and Objects
- Inheritance
- Polymorphism
- Encapsulation -
Explore Advanced Topics
- Pointers and References
- Dynamic Memory
- STL (Containers, Algorithms)
- Templates
- File I/O -
Build Projects
- Calculator
- To-Do List
- Game (Tic-Tac-Toe, Snake)
- Student Management System
๐ก Tips for Success:
- ๐ฅ Code daily - Even 30 minutes helps!
- ๐ Read others' code - Learn different approaches
- ๐ Debug actively - Understand your errors
- ๐ค Collaborate - Join coding communities
- ๐ Never stop learning - Technology evolves!
๐ 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! ๐ป๐