Arrays

Introduction to Arrays

Arrays are collections of elements of the same data type stored in contiguous memory locations. They provide constant-time access to elements by index.

Array Declaration and Initialization

Arrays can be declared and initialized in several ways:

Array Declaration

#include <iostream>
using namespace std;

int main() {
    // Method 1: Declaration with size
    int numbers[5];
    
    // Method 2: Declaration with initialization
    int scores[5] = {95, 87, 92, 78, 85};
    
    // Method 3: Let compiler determine size
    int grades[] = {90, 88, 95, 92, 87};
    
    // Method 4: Partial initialization (remaining elements are 0)
    int values[10] = {1, 2, 3};  // Only first 3 elements initialized
    
    // Method 5: Initialize all elements to 0
    int zeros[5] = {0};  // All elements become 0
    
    // Print scores array
    cout << "Scores: ";
    for (int i = 0; i < 5; i++) {
        cout << scores[i] << " ";
    }
    cout << endl;
    
    // Print size of grades array
    cout << "Size of grades array: " << sizeof(grades)/sizeof(grades[0]) << endl;
    
    return 0;
}

Array Operations

Common array operations include accessing, modifying, and iterating through elements:

Array Operations

#include <iostream>
using namespace std;

int main() {
    int arr[5] = {10, 20, 30, 40, 50};
    int size = 5;
    
    // Accessing elements
    cout << "First element: " << arr[0] << endl;
    cout << "Last element: " << arr[size-1] << endl;
    
    // Modifying elements
    arr[2] = 35;  // Change third element
    cout << "Modified third element: " << arr[2] << endl;
    
    // Iterating through array
    cout << "All elements: ";
    for (int i = 0; i < size; i++) {
        cout << arr[i] << " ";
    }
    cout << endl;
    
    // Range-based for loop (C++11)
    cout << "Using range-based for: ";
    for (int element : arr) {
        cout << element << " ";
    }
    cout << endl;
    
    return 0;
}

Multidimensional Arrays

C++ supports multidimensional arrays, commonly used for matrices and tables:

2D Array Example

#include <iostream>
using namespace std;

int main() {
    // 2D array declaration and initialization
    int matrix[3][4] = {
        {1, 2, 3, 4},
        {5, 6, 7, 8},
        {9, 10, 11, 12}
    };
    
    int rows = 3, cols = 4;
    
    // Print the matrix
    cout << "Matrix:" << endl;
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            cout << matrix[i][j] << "\t";
        }
        cout << endl;
    }
    
    // Access specific element
    cout << "Element at (1,2): " << matrix[1][2] << endl;
    
    // Modify element
    matrix[0][0] = 100;
    cout << "Modified element at (0,0): " << matrix[0][0] << endl;
    
    // Sum of all elements
    int sum = 0;
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            sum += matrix[i][j];
        }
    }
    cout << "Sum of all elements: " << sum << endl;
    
    return 0;
}

Array Algorithms

Common algorithms performed on arrays include searching, sorting, and finding extremes:

Array Algorithms

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

// Linear search
int linearSearch(int arr[], int size, int target) {
    for (int i = 0; i < size; i++) {
        if (arr[i] == target) {
            return i;  // Return index if found
        }
    }
    return -1;  // Return -1 if not found
}

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

// Reverse array
void reverseArray(int arr[], int size) {
    int start = 0, end = size - 1;
    while (start < end) {
        swap(arr[start], arr[end]);
        start++;
        end--;
    }
}

int main() {
    int arr[] = {64, 34, 25, 12, 22, 11, 90};
    int size = sizeof(arr)/sizeof(arr[0]);
    
    cout << "Original array: ";
    for (int i = 0; i < size; i++) {
        cout << arr[i] << " ";
    }
    cout << endl;
    
    // Linear search
    int target = 25;
    int index = linearSearch(arr, size, target);
    if (index != -1) {
        cout << "Element " << target << " found at index: " << index << endl;
    } else {
        cout << "Element " << target << " not found" << endl;
    }
    
    // Find maximum
    int max = findMax(arr, size);
    cout << "Maximum element: " << max << endl;
    
    // Reverse array
    reverseArray(arr, size);
    cout << "Reversed array: ";
    for (int i = 0; i < size; i++) {
        cout << arr[i] << " ";
    }
    cout << endl;
    
    return 0;
}

Array vs Other Data Structures

Operation Array Vector Linked List
Access by index O(1) O(1) O(n)
Insert at beginning O(n) O(n) O(1)
Insert at end O(1) O(1) amortized O(n)
Delete element O(n) O(n) O(1)
Memory overhead Low Medium High

Best Practices

  • Always check array bounds to avoid buffer overflow
  • Initialize arrays to avoid garbage values
  • Use const for arrays that should not be modified
  • Consider using std::array or std::vector for better safety
  • Use meaningful variable names for array indices