C++ Arrays

Welcome to The Coding College! In this tutorial, we’ll cover the basics of arrays in C++, their uses, and practical examples. Arrays are a fundamental data structure in C++ that allow you to store multiple values in a single variable, making them essential for efficient programming.

What is an Array?

An array is a collection of elements of the same data type, stored in contiguous memory locations. You can think of it as a list where each item can be accessed using an index.

Syntax

data_type array_name[size];
  • data_type: The type of elements (e.g., int, float, char).
  • array_name: The name of the array.
  • size: The number of elements the array can hold.

Example: Declare and Initialize an Array

#include <iostream>
using namespace std;

int main() {
    int numbers[5] = {10, 20, 30, 40, 50};  // Initialize array

    for (int i = 0; i < 5; i++) {
        cout << "Element at index " << i << ": " << numbers[i] << endl;
    }

    return 0;
}

Output:

Element at index 0: 10  
Element at index 1: 20  
Element at index 2: 30  
Element at index 3: 40  
Element at index 4: 50

Types of Arrays in C++

1. Single-Dimensional Arrays

A linear list of elements.

Example:

int arr[3] = {1, 2, 3};

2. Multi-Dimensional Arrays

Arrays with more than one dimension, such as matrices.

Example (2D Array):

int matrix[2][3] = {
    {1, 2, 3},
    {4, 5, 6}
};

3. Dynamic Arrays

Arrays where size can be adjusted at runtime (using pointers or STL).

Accessing Array Elements

Array elements are accessed using their index, starting from 0.

#include <iostream>
using namespace std;

int main() {
    int arr[3] = {5, 10, 15};
    cout << "First element: " << arr[0] << endl;  // Access element at index 0
    return 0;
}

Output:

First element: 5

Array Operations

1. Traversing an Array

#include <iostream>
using namespace std;

int main() {
    int arr[5] = {10, 20, 30, 40, 50};

    cout << "Array elements:" << endl;
    for (int i = 0; i < 5; i++) {
        cout << arr[i] << " ";
    }
    return 0;
}

Output:

Array elements: 10 20 30 40 50

2. Sum of Array Elements

#include <iostream>
using namespace std;

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

    for (int i = 0; i < 4; i++) {
        sum += arr[i];
    }

    cout << "Sum of elements: " << sum << endl;
    return 0;
}

Output:

Sum of elements: 10

3. Finding the Maximum Element

#include <iostream>
using namespace std;

int main() {
    int arr[5] = {12, 34, 10, 56, 45};
    int max = arr[0];

    for (int i = 1; i < 5; i++) {
        if (arr[i] > max) {
            max = arr[i];
        }
    }

    cout << "Maximum element: " << max << endl;
    return 0;
}

Output:

Maximum element: 56

Multi-Dimensional Arrays

Example: 2D Array

#include <iostream>
using namespace std;

int main() {
    int matrix[2][3] = {
        {1, 2, 3},
        {4, 5, 6}
    };

    cout << "2D Array elements:" << endl;
    for (int i = 0; i < 2; i++) {
        for (int j = 0; j < 3; j++) {
            cout << matrix[i][j] << " ";
        }
        cout << endl;
    }
    return 0;
}

Output:

2D Array elements:  
1 2 3  
4 5 6

Common Mistakes with Arrays

  • Accessing Out-of-Bounds Elements:
    Accessing an index beyond the array size leads to undefined behavior.
int arr[3] = {1, 2, 3};
cout << arr[3];  // Error: Out of bounds
  • Uninitialized Arrays:
    Declaring an array without initializing can lead to garbage values.
int arr[3];  // Contains undefined values
  • Mismatched Size and Elements:
    Declaring an array with a specific size but initializing with more elements will cause a compilation error.
int arr[2] = {1, 2, 3};  // Error: Too many elements

Arrays vs Other Data Structures

FeatureArraysVectors (STL)Linked Lists
SizeFixed at declarationDynamicDynamic
Access TimeO(1) (Random Access)O(1)O(n)
Insertion/DeletionSlow (O(n))Efficient (O(1) end)Efficient
Memory UsageContiguousContiguousNon-contiguous

Real-World Applications of Arrays

  1. Storing a List of Values: For example, the scores of students in a class.
  2. Matrix Operations: Multi-dimensional arrays are used for image processing, game development, and scientific simulations.
  3. Efficient Searching and Sorting: Arrays are often used in algorithms like binary search and quicksort.

Explore More at The Coding College

Visit The Coding College for more in-depth tutorials and practical programming insights.

What’s Next?

  • Learn about dynamic arrays using pointers.
  • Explore STL vectors as a more flexible alternative.
  • Understand advanced array algorithms, like searching and sorting.

Leave a Comment