Course offer · HLD · LLD · System Design at ₹799 until 30 Nov (not interview packs)

C++ Programming

Arrays and Strings

Mastering arrays and strings concepts and implementation.

On this page

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:

1type arrayName[size];

Example:

1int numbers[5];           // Array of 5 integers
2double prices[10];        // Array of 10 doubles
3char letters[26];         // Array of 26 characters

Array Initialization

Method 1: Initialize at declaration

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

Method 2: Initialize later

1int arr[5];
2arr[0] = 10;
3arr[1] = 20;
4// ...

Accessing Array Elements

Arrays use zero-based indexing:

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

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

Array Size

Get size:

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

Note: This only works for arrays, not pointers!

Common Array Operations

Traversing Array:

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

Finding Maximum:

1int arr[5] = {10, 5, 20, 15, 8};
2int max = arr[0];
3for (int i = 1; i < 5; i++) {
4    if (arr[i] > max) {
5        max = arr[i];
6    }
7}

Sum of Elements:

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

Multi-dimensional Arrays

2D Array (Matrix):

1int matrix[3][4] = {
2    {1, 2, 3, 4},
3    {5, 6, 7, 8},
4    {9, 10, 11, 12}
5};
6 
7// Access element
8cout << matrix[1][2] << endl;  // 7

Traversing 2D Array:

1for (int i = 0; i < 3; i++) {
2    for (int j = 0; j < 4; j++) {
3        cout << matrix[i][j] << " ";
4    }
5    cout << endl;
6}

Arrays as Function Parameters

Passing arrays to functions:

1void printArray(int arr[], int size) {
2    for (int i = 0; i < size; i++) {
3        cout << arr[i] << " ";
4    }
5}
6 
7int main() {
8    int arr[5] = {1, 2, 3, 4, 5};
9    printArray(arr, 5);
10    return 0;
11}

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:

1char str1[20] = "Hello";
2char str2[] = "World";
3char str3[10] = {'H', 'e', 'l', 'l', 'o', '\0'};

Common Functions (from <cstring>):

1#include <cstring>
2 
3char str1[20] = "Hello";
4char str2[20] = "World";
5 
6strlen(str1);           // Length: 5
7strcpy(str1, str2);      // Copy str2 to str1
8strcat(str1, str2);      // Concatenate str2 to str1
9strcmp(str1, str2);      // Compare: 0 if equal

C++ String Class

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

Declaration:

1#include <string>
2using namespace std;
3 
4string str1 = "Hello";
5string str2("World");
6string str3;

Common Operations:

Length:

1string str = "Hello";
2int len = str.length();  // or str.size()

Concatenation:

1string str1 = "Hello";
2string str2 = "World";
3string result = str1 + " " + str2;  // "Hello World"
4str1 += str2;  // Append

Accessing Characters:

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

Comparison:

1string str1 = "Hello";
2string str2 = "World";
3if (str1 == str2) { }      // Equal
4if (str1 < str2) { }       // Less than (lexicographic)
5if (str1.compare(str2) == 0) { }  // Compare method

Substring:

1string str = "Hello World";
2string sub = str.substr(0, 5);      // "Hello"
3string sub2 = str.substr(6);       // "World"

Finding:

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

Replacing:

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

Inserting:

1string str = "Hello";
2str.insert(5, " World");  // "Hello World"

Erasing:

1string str = "Hello World";
2str.erase(5, 6);  // "Hello"

String Input/Output

Reading strings:

1string name;
2cin >> name;              // Reads until whitespace
3getline(cin, name);       // Reads entire line
4getline(cin, name, ',');  // Reads until comma

Example:

1string firstName, lastName;
2cout << "Enter first name: ";
3cin >> firstName;
4cout << "Enter last name: ";
5cin >> lastName;
6 
7string fullName = firstName + " " + lastName;
8cout << "Full name: " << fullName << endl;

Sample Output

Enter first name: 
Enter last name: 
Full name:

String Iteration

Using index:

1string str = "Hello";
2for (int i = 0; i < str.length(); i++) {
3    cout << str[i] << " ";
4}

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

1string str = "Hello";
2for (char c : str) {
3    cout << c << " ";
4}

Using iterators:

1string str = "Hello";
2for (auto it = str.begin(); it != str.end(); ++it) {
3    cout << *it << " ";
4}

Common Patterns

Pattern 1: Reverse String

1string str = "Hello";
2string reversed = "";
3for (int i = str.length() - 1; i >= 0; i--) {
4    reversed += str[i];
5}

Pattern 2: Count Characters

1string str = "Hello World";
2int count = 0;
3for (char c : str) {
4    if (c == 'l') count++;
5}

Pattern 3: Check Palindrome

1bool isPalindrome(string str) {
2    int left = 0;
3    int right = str.length() - 1;
4    while (left < right) {
5        if (str[left] != str[right]) {
6            return false;
7        }
8        left++;
9        right--;
10    }
11    return true;
12}

Pattern 4: Split String

1vector<string> split(string str, char delimiter) {
2    vector<string> tokens;
3    string token = "";
4    for (char c : str) {
5        if (c == delimiter) {
6            tokens.push_back(token);
7            token = "";
8        } else {
9            token += c;
10        }
11    }
12    tokens.push_back(token);
13    return tokens;
14}

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.

Sample Output

First element: 10
Last element: 50
All elements: 10 20 30 40 50 
After modification: 10 20 99 40 50 
Sum: 219