Arrays in C++

 Arrays in C++

 ·       Derived data structure.

·       A collection of elements of the same data type stored in contiguous memory locations

·       Each element can be accessed using an index (or indices in multi-dimensional arrays).

·       Fixed in size (for static arrays) or can be dynamically resized (using dynamic memory allocation or `std::vector`).

 

Key Characteristics

·       Fixed Size (for static arrays):

·       The size is determined at compile-time and cannot be changed.

·       Contiguous Memory Elements are stored next to each other in memory, enabling fast access via index.

·       Zero-Based Indexing In C++, array indices start at 0.

 

Syntax

data_type array_name[size];

 

Examples

int numbers[5]; // Declares an array of 5 integers

float temperatures[10]; // Declares an array of 10 floats

char letters[3]; // Declares an array of 3 characters

 

Initialization

Arrays can be initialized at declaration:

// Initialize all elements explicitly

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

 

// Partial initialization (remaining elements are set to 0)

int numbers[5] = {1, 2}; // {1, 2, 0, 0, 0}

 

// Initialize all elements to 0

int zeros[5] = {0};

 

// Size can be omitted if initializer list is provided

int numbers[] = {1, 2, 3, 4, 5}; // Size inferred as 5

---

 

Accessing Array Elements

Using the array name and an index in square brackets (`[]`).

int numbers[5] = {10, 20, 30, 40, 50};

cout << numbers[0]; // Outputs 10

numbers[2] = 100; // Assigns 100 to the third element

---

Input and Output Using Loop

#include <iostream>

using namespace std;

 

int main() {

    int n[5];

    cout << "Enter 5 numbers: ";

   

    for(int i = 0; i < 5; i++) {

        cin >> n[i];

    }

   

    cout << "You entered: ";

    for(int i = 0; i < 5; i++) {

        cout << n[i] << " ";

    }

    return 0;

}

 

Array Example – Sum of Elements

#include <iostream>

using namespace std;

 

int main() {

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

    int sum = 0;

 

    for(int i = 0; i < 5; i++) {

        sum += num[i];

    }

 

    cout << "Sum = " << sum;

    return 0;

}

🧾 Output:

Sum = 15

 

Types of Arrays

Single-Dimensional Arrays

A linear collection of elements.

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

 

Multi-Dimensional Arrays

Arrays with more than one dimension, such as 2D (matrices) or 3D arrays.

 

2D Array

int matrix[3][3];

This defines a 3×3 matrix:

Row\Col

0

1

2

0

matrix[0][0]

matrix[0][1]

matrix[0][2]

1

matrix[1][0]

matrix[1][1]

matrix[1][2]

2

matrix[2][0]

matrix[2][1]

matrix[2][2]


2D Array Declaration

datatype array_name[rows][columns];

Example:

int a[2][3];    // 2 rows, 3 columns


Initialisation (Static)

int a[2][3] = {

    {1, 2, 3},

    {4, 5, 6}

};

You can also write:

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


Accessing 2D Array Elements

Access using two indices: one for row, one for column.

cout << a[0][2]; // prints 3


Input and Output Using Loops

#include <iostream>

using namespace std;

 

int main() {

    int a[2][3];

 

    cout << "Enter elements of 2x3 matrix:\n";

    for(int i = 0; i < 2; i++) {

        for(int j = 0; j < 3; j++) {

            cin >> a[i][j];

        }

    }

 

    cout << "\nMatrix is:\n";

    for(int i = 0; i < 2; i++) {

        for(int j = 0; j < 3; j++) {

            cout << a[i][j] << " ";

        }

        cout << endl;

    }

}

🧾 Output:

Enter elements of 2x3 matrix:

1 2 3

4 5 6

 

Matrix is:

1 2 3

4 5 6



Declaration of a 3D Array

Syntax:

datatype array_name[depth][rows][columns];

Example:

int cube[2][3][4];

Here:

  • 2 → number of layers (depth)
  • 3 → number of rows per layer
  • 4 → number of columns per row

So total elements = 2 × 3 × 4 = 24 elements.


Initialisation of 3D Array

int cube[2][2][3] = {

    { {1, 2, 3}, {4, 5, 6} },   // Layer 0

    { {7, 8, 9}, {10, 11, 12} } // Layer 1

};


Practical Example – Display 3D Array

#include <iostream>

using namespace std;

 

int main() {

    int cube[2][2][3] = {

        { {1, 2, 3}, {4, 5, 6} },

        { {7, 8, 9}, {10, 11, 12} }

    };

 

    // Printing the 3D array elements

    for (int i = 0; i < 2; i++) {          // Layers

        cout << "Layer " << i + 1 << ":\n";

        for (int j = 0; j < 2; j++) {      // Rows

            for (int k = 0; k < 3; k++) {  // Columns

                cout << cube[i][j][k] << " ";

            }

            cout << endl;

        }

        cout << endl;

    }

 

    return 0;

}


Output:

Layer 1:

1 2 3

4 5 6

 

Layer 2:

7 8 9

10 11 12



Real-Life Analogy

Think of a 3D array like:

  • Bookshelf (Layer)
  • Shelves inside it (Rows)
  • Books on each shelf (Columns)

So, to pick one book:
cube[layer][shelf][book]


Use Cases

  • Storing marks, salaries, ages, IDs, etc.
  • Matrices and image data in graphics.
  • Storing strings (as character arrays).
  • Buffers in communication programs.

================================================================== 

Post a Comment

0 Comments