Arrays and Strings

Back

Loading concept...

🏠 Arrays & Strings in C++

Your Collection of Treasures in Neat Little Boxes


The Big Idea πŸ’‘

Imagine you have a toy box with numbered compartments. Each compartment holds exactly one toy, and you can find any toy instantly by knowing its number. That’s an array! And when those toys are letters that spell words? That’s a string!


🎯 What You’ll Learn

  1. Arrays – Your numbered collection boxes
  2. Multidimensional Arrays – Boxes inside boxes (like a grid)
  3. std::string Class – C++'s smart word container
  4. String Operations – Playing with words

πŸ“¦ Part 1: Arrays

What is an Array?

Think of a row of mailboxes at an apartment building. Each mailbox:

  • Has a number (starting from 0, not 1!)
  • Holds one item of the same type
  • Is right next to its neighbors
// Creating 5 mailboxes for integers
int scores[5];

// Putting values in each mailbox
scores[0] = 95;  // First box
scores[1] = 87;  // Second box
scores[2] = 92;  // Third box
scores[3] = 78;  // Fourth box
scores[4] = 88;  // Fifth box

🎁 Creating Arrays

Method 1: Empty boxes, fill later

int ages[4];      // 4 empty boxes
ages[0] = 10;     // Now filling them
ages[1] = 12;
ages[2] = 8;
ages[3] = 15;

Method 2: Boxes with gifts already inside

int ages[4] = {10, 12, 8, 15};

Method 3: Let C++ count for you

int ages[] = {10, 12, 8, 15};
// C++ knows there are 4 items!

πŸ”’ Array Indexing

SUPER IMPORTANT: Arrays start counting from 0, not 1!

graph TD A["Array: pets"] --> B["Index 0<br>πŸ• dog"] A --> C["Index 1<br>🐱 cat"] A --> D["Index 2<br>🐦 bird"] A --> E["Index 3<br>🐹 hamster"]
string pets[4] = {"dog", "cat", "bird", "hamster"};

cout << pets[0];  // Prints: dog
cout << pets[2];  // Prints: bird
cout << pets[3];  // Prints: hamster

⚠️ Array Danger Zone!

Going outside your array is like opening a mailbox that doesn’t exist!

int nums[3] = {10, 20, 30};
// nums[0] = 10 βœ…
// nums[1] = 20 βœ…
// nums[2] = 30 βœ…
// nums[3] = ??? ❌ DANGER! No box #3!

πŸ”„ Looping Through Arrays

Visit every mailbox automatically!

int scores[5] = {95, 87, 92, 78, 88};

// Visit each box
for(int i = 0; i < 5; i++) {
    cout << "Box " << i << ": ";
    cout << scores[i] << endl;
}

Output:

Box 0: 95
Box 1: 87
Box 2: 92
Box 3: 78
Box 4: 88

🏒 Part 2: Multidimensional Arrays

What Are They?

Remember our mailboxes? Now imagine a whole apartment building with mailboxes on every floor!

  • 1D Array = One row of mailboxes
  • 2D Array = A grid (rows Γ— columns)
  • 3D Array = A cube of boxes!

πŸ“Š 2D Arrays: The Grid

Think of a tic-tac-toe board or a spreadsheet!

graph TD A["2D Array: grid[3][3]"] --> B["Row 0"] A --> C["Row 1"] A --> D["Row 2"] B --> B1["[0][0]"] --> B2["[0][1]"] --> B3["[0][2]"] C --> C1["[1][0]"] --> C2["[1][1]"] --> C3["[1][2]"] D --> D1["[2][0]"] --> D2["[2][1]"] --> D3["[2][2]"]

Creating a 2D Array

// A 3x3 grid (like tic-tac-toe)
int grid[3][3] = {
    {1, 2, 3},    // Row 0
    {4, 5, 6},    // Row 1
    {7, 8, 9}     // Row 2
};

// Access: grid[row][column]
cout << grid[0][0];  // 1 (top-left)
cout << grid[1][1];  // 5 (center)
cout << grid[2][2];  // 9 (bottom-right)

Real Example: Student Grades

// 3 students, 4 tests each
int grades[3][4] = {
    {90, 85, 92, 88},  // Student 0
    {78, 82, 79, 85},  // Student 1
    {95, 98, 94, 96}   // Student 2
};

// Get Student 2's Test 3 score
cout << grades[2][3];  // Output: 96

Looping Through 2D Arrays

// Print entire grid
for(int row = 0; row < 3; row++) {
    for(int col = 0; col < 4; col++) {
        cout << grades[row][col] << " ";
    }
    cout << endl;  // New line after each row
}

🧊 3D Arrays (Bonus!)

Like a Rubik’s cube – layers of grids!

// 2 floors, each with 3x3 grid
int cube[2][3][3];

// Access: cube[floor][row][column]
cube[0][1][2] = 42;  // Floor 0, Row 1, Col 2

πŸ“ Part 3: The std::string Class

Goodbye Character Arrays, Hello string!

Old way (hard):

char name[20] = "Alice";  // Fixed size, tricky to use

New way (easy!):

#include <string>
string name = "Alice";  // Grows as needed!

🌟 Why string is Amazing

Old char[] Way New string Way
Fixed size Grows automatically
Manual memory Handles itself
Hard to combine Easy concatenation
Confusing length Simple .length()

Creating Strings

#include <string>
using namespace std;

// Different ways to create strings
string empty;               // ""
string greeting = "Hello";  // "Hello"
string name("Alice");       // "Alice"
string stars(5, '*');       // "*****"

πŸ“ String Properties

string word = "Rainbow";

// Length (how many letters)
cout << word.length();  // 7
cout << word.size();    // 7 (same thing!)

// Is it empty?
cout << word.empty();   // false (0)

// Access individual letters
cout << word[0];        // 'R'
cout << word[3];        // 'n'
cout << word.at(6);     // 'w' (safer!)

🎯 at() vs [] - What’s the Difference?

string s = "Hi";

// Both work normally:
cout << s[0];      // 'H'
cout << s.at(0);   // 'H'

// But with bad index:
cout << s[99];     // ❌ Random garbage!
cout << s.at(99);  // βœ… Throws error (safer!)

πŸ”§ Part 4: String Operations

βž• Combining Strings (Concatenation)

Like snapping LEGO bricks together!

string first = "Hello";
string second = "World";

// Method 1: Plus sign
string result = first + " " + second;
// result = "Hello World"

// Method 2: append()
first.append(" there!");
// first = "Hello there!"

// Method 3: +=
first += "!!!";
// first = "Hello there!!!!"

πŸ” Finding Things in Strings

string sentence = "I love pizza and pasta";

// Find position of a word
size_t pos = sentence.find("pizza");
// pos = 7 (pizza starts at index 7)

// Word not found?
pos = sentence.find("burger");
// pos = string::npos (special "not found" value)

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

βœ‚οΈ Cutting Strings (Substring)

string text = "Hello World";

// substr(start, length)
string piece = text.substr(0, 5);
// piece = "Hello"

string end = text.substr(6, 5);
// end = "World"

// From position to end
string rest = text.substr(6);
// rest = "World"

πŸ”„ Replacing Parts

string msg = "I love cats";

// replace(start, length, new_text)
msg.replace(7, 4, "dogs");
// msg = "I love dogs"

πŸ—‘οΈ Inserting & Erasing

string word = "Hllo";

// Insert at position
word.insert(1, "e");
// word = "Hello"

// Erase from position
word.erase(0, 1);
// word = "ello"

πŸ”€ Comparing Strings

string a = "apple";
string b = "banana";

// Using compare()
if(a.compare(b) < 0) {
    cout << "apple comes first";
}

// Simpler way!
if(a < b) {
    cout << "apple comes first";
}
if(a == "apple") {
    cout << "It's an apple!";
}

🎀 Reading Strings from User

string name;

// Single word (stops at space)
cin >> name;

// Full line (includes spaces)
getline(cin, name);

πŸ”’ Converting Numbers ↔ Strings

// Number to string
int age = 25;
string ageText = to_string(age);
// ageText = "25"

// String to number
string numStr = "42";
int num = stoi(numStr);   // String to int
double d = stod("3.14");  // String to double

🎯 Quick Reference

graph LR A["C++ Containers"] --> B["Arrays"] A --> C["Strings"] B --> B1["1D: int arr[5]"] B --> B2["2D: int grid[3][3]"] B --> B3["Index starts at 0"] C --> C1["&#35;35;include &amp;lt;string&amp;gt;"] C --> C2["Grows automatically"] C --> C3["Many built-in functions"]

🌟 You Did It!

You now understand:

  • βœ… Arrays are numbered boxes holding same-type items
  • βœ… Index starts at 0, not 1!
  • βœ… 2D arrays are grids (rows Γ— columns)
  • βœ… string is smarter than char[]
  • βœ… Strings can be cut, combined, searched, and compared

Remember: Arrays are like apartment mailboxes. Strings are like magical stretchy word containers. Both help you organize data like a pro! πŸš€

Loading story...

Story - Premium Content

Please sign in to view this story and start learning.

Upgrade to Premium to unlock full access to all stories.

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.