06

Module 6: Arrays and Strings

Chapter 6 • Beginner

50 min

Arrays and Strings

Arrays and strings are fundamental data structures for storing collections of data. Understanding them is crucial for C++ programming.

Arrays

An array is a collection of elements of the same type stored in contiguous memory locations.

Array Declaration

Syntax:

cpp.js
type arrayName[size];

Example:

cpp.js
int numbers[5];           // Array of 5 integers
double prices[10];        // Array of 10 doubles
char letters[26];         // Array of 26 characters

Array Initialization

Method 1: Initialize at declaration

cpp.js
int arr[5] = {1, 2, 3, 4, 5};
int arr2[] = {1, 2, 3};  // Size automatically determined
int arr3[5] = {1, 2};    // Rest filled with 0

Method 2: Initialize later

cpp.js
int arr[5];
arr[0] = 10;
arr[1] = 20;
// ...

Accessing Array Elements

Arrays use zero-based indexing:

cpp.js
int arr[5] = {10, 20, 30, 40, 50};
cout << arr[0] << endl;  // First element: 10
cout << arr[4] << endl;  // Last element: 50

Important: Array indices range from 0 to size - 1.

Array Size

Get size:

cpp.js
int arr[5] = {1, 2, 3, 4, 5};
int size = sizeof(arr) / sizeof(arr[0]);  // 5

Note: This only works for arrays, not pointers!

Common Array Operations

Traversing Array:

cpp.js
int arr[5] = {1, 2, 3, 4, 5};
for (int i = 0; i < 5; i++) {
    cout << arr[i] << " ";
}

Finding Maximum:

cpp.js
int arr[5] = {10, 5, 20, 15, 8};
int max = arr[0];
for (int i = 1; i < 5; i++) {
    if (arr[i] > max) {
        max = arr[i];
    }
}

Sum of Elements:

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

Multi-dimensional Arrays

2D Array (Matrix):

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

// Access element
cout << matrix[1][2] << endl;  // 7

Traversing 2D Array:

cpp.js
for (int i = 0; i < 3; i++) {
    for (int j = 0; j < 4; j++) {
        cout << matrix[i][j] << " ";
    }
    cout << endl;
}

Arrays as Function Parameters

Passing arrays to functions:

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

int main() {
    int arr[5] = {1, 2, 3, 4, 5};
    printArray(arr, 5);
    return 0;
}

Note: Arrays are passed by reference (pointer) by default!

Strings

In C++, strings can be handled in two ways:

  1. C-style strings (character arrays)
  2. C++ string class (recommended)

C-style Strings

Character arrays ending with null terminator (\0):

Declaration:

cpp.js
char str1[20] = "Hello";
char str2[] = "World";
char str3[10] = {'H', 'e', 'l', 'l', 'o', '\0'};

Common Functions (from <cstring>):

cpp.js
#include <cstring>

char str1[20] = "Hello";
char str2[20] = "World";

strlen(str1);           // Length: 5
strcpy(str1, str2);      // Copy str2 to str1
strcat(str1, str2);      // Concatenate str2 to str1
strcmp(str1, str2);      // Compare: 0 if equal

C++ String Class

Modern, safer way to handle strings (from <string>):

Declaration:

cpp.js
#include <string>
using namespace std;

string str1 = "Hello";
string str2("World");
string str3;

Common Operations:

Length:

cpp.js
string str = "Hello";
int len = str.length();  // or str.size()

Concatenation:

cpp.js
string str1 = "Hello";
string str2 = "World";
string result = str1 + " " + str2;  // "Hello World"
str1 += str2;  // Append

Accessing Characters:

cpp.js
string str = "Hello";
char first = str[0];      // 'H'
char last = str[str.length() - 1];  // 'o'
str[0] = 'h';  // Modify

Comparison:

cpp.js
string str1 = "Hello";
string str2 = "World";
if (str1 == str2) { }      // Equal
if (str1 < str2) { }       // Less than (lexicographic)
if (str1.compare(str2) == 0) { }  // Compare method

Substring:

cpp.js
string str = "Hello World";
string sub = str.substr(0, 5);      // "Hello"
string sub2 = str.substr(6);       // "World"

Finding:

cpp.js
string str = "Hello World";
int pos = str.find("World");       // 6
int pos2 = str.find("xyz");        // string::npos (not found)

Replacing:

cpp.js
string str = "Hello World";
str.replace(6, 5, "C++");  // "Hello C++"

Inserting:

cpp.js
string str = "Hello";
str.insert(5, " World");  // "Hello World"

Erasing:

cpp.js
string str = "Hello World";
str.erase(5, 6);  // "Hello"

String Input/Output

Reading strings:

cpp.js
string name;
cin >> name;              // Reads until whitespace
getline(cin, name);       // Reads entire line
getline(cin, name, ',');  // Reads until comma

Example:

cpp.js
string firstName, lastName;
cout << "Enter first name: ";
cin >> firstName;
cout << "Enter last name: ";
cin >> lastName;

string fullName = firstName + " " + lastName;
cout << "Full name: " << fullName << endl;

String Iteration

Using index:

cpp.js
string str = "Hello";
for (int i = 0; i < str.length(); i++) {
    cout << str[i] << " ";
}

Using range-based for (C++11):

cpp.js
string str = "Hello";
for (char c : str) {
    cout << c << " ";
}

Using iterators:

cpp.js
string str = "Hello";
for (auto it = str.begin(); it != str.end(); ++it) {
    cout << *it << " ";
}

Common Patterns

Pattern 1: Reverse String

cpp.js
string str = "Hello";
string reversed = "";
for (int i = str.length() - 1; i >= 0; i--) {
    reversed += str[i];
}

Pattern 2: Count Characters

cpp.js
string str = "Hello World";
int count = 0;
for (char c : str) {
    if (c == 'l') count++;
}

Pattern 3: Check Palindrome

cpp.js
bool isPalindrome(string str) {
    int left = 0;
    int right = str.length() - 1;
    while (left < right) {
        if (str[left] != str[right]) {
            return false;
        }
        left++;
        right--;
    }
    return true;
}

Pattern 4: Split String

cpp.js
vector<string> split(string str, char delimiter) {
    vector<string> tokens;
    string token = "";
    for (char c : str) {
        if (c == delimiter) {
            tokens.push_back(token);
            token = "";
        } else {
            token += c;
        }
    }
    tokens.push_back(token);
    return tokens;
}

Best Practices

  1. Use C++ string class instead of C-style strings when possible
  2. Check bounds when accessing array elements
  3. Initialize arrays to avoid garbage values
  4. Use meaningful names for arrays and strings
  5. Prefer range-based for loops for iteration
  6. Use `size()` or `length()` for string length
  7. Be careful with array size - no automatic bounds checking
  8. Use `std::vector` for dynamic arrays (we'll cover this later)

Common Mistakes

  • ❌ Array index out of bounds
  • ❌ Forgetting null terminator in C-style strings
  • ❌ Using = to compare C-style strings (use strcmp)
  • ❌ Not checking if string is empty before operations
  • ❌ Mixing C-style and C++ strings incorrectly
  • ❌ Forgetting to include <string> header

Next Module

In Module 7, we'll learn about Pointers and References - how to work with memory addresses and create more efficient programs!

Hands-on Examples

Basic Array Operations

#include <iostream>
using namespace std;

int main() {
    // Array declaration and initialization
    int arr[5] = {10, 20, 30, 40, 50};
    
    // Accessing elements
    cout << "First element: " << arr[0] << endl;
    cout << "Last element: " << arr[4] << endl;
    
    // Traversing array
    cout << "All elements: ";
    for (int i = 0; i < 5; i++) {
        cout << arr[i] << " ";
    }
    cout << endl;
    
    // Modifying elements
    arr[2] = 99;
    cout << "After modification: ";
    for (int i = 0; i < 5; i++) {
        cout << arr[i] << " ";
    }
    cout << endl;
    
    // Finding sum
    int sum = 0;
    for (int i = 0; i < 5; i++) {
        sum += arr[i];
    }
    cout << "Sum: " << sum << endl;
    
    return 0;
}

Arrays store multiple values of the same type. Elements are accessed using zero-based indexing. Arrays are useful for storing collections of data that you need to process together.