Arrays in C Programming

1. Single Dimensional Array

A single-dimensional array is a list of elements of the same type stored in contiguous memory locations. It is also known as a one-dimensional array.

Declaration:

int arr[5];

Initialization:

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

Accessing Elements:

for (int i = 0; i < 5; i++) {
  printf("%d ", arr[i]);
}

Use Cases:

2. Double Dimensional Array (2D Array)

A 2D array is an array of arrays. It can be visualized as a matrix with rows and columns.

Declaration:

int matrix[3][4];

Initialization:

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

Accessing Elements:

How to access Elements
for (int i = 0; i < 2; i++) {
  for (int j = 0; j < 3; j++) {
    printf("%d ", matrix[i][j]);
  }
}

Use Cases:

3. Multi Dimensional Array

Multi-dimensional arrays can have more than two dimensions. Mostly used are 3D arrays which can be visualized as a collection of 2D matrices.

Declaration:

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

Initialization:

int cube[2][2][2] = {
  {
    {1, 2},
    {3, 4}
  },
  {
    {5, 6},
    {7, 8}
  }
};

Accessing Elements:

for (int i = 0; i < 2; i++) {
  for (int j = 0; j < 2; j++) {
    for (int k = 0; k < 2; k++) {
      printf("%d ", cube[i][j][k]);
    }
  }
}

Use Cases: