Introduction

Multidimensional arrays are supported by the C programming language. Here is a declaration for a multidimensional array in its generic form:

type name[size1][size2]...[sizeN];

For instance, the declaration that follows produces a three-dimensional integer array.

int threeD[5][10][4];

2D Arrays Introduction

A two-dimensional array is a nested array of 1D arrays. You would write the following to define a two-dimensional integer array of size [x][y]:

type arrayName [ x ][ y ];

Where type can be any legal data type recognised by C, and arrayName is a legal C identifier. A table with x number of rows and y number of columns can be compared to a two-dimensional array. Here is an example of a two-dimensional array with 3 rows and 4 columns:

Two Dimensional Arrays in C

Since "a" is the name of the array and "I" and "j" are the subscripts that specifically identify each element in "a," each element in the array is addressed with notationa[i][j].

Initializing Two-Dimensional Arrays

The initialization of multidimensional arrays is done by giving square brackets values for each row.


int BoardInfinityArray[3][4] = { 
  {0, 1, 2, 3} , 
  {4, 5, 6, 7} , 
  {8, 9, 10, 11}   

};

The targeted row may be identified without using the nested brackets. The next initialization is identical to the preceding one:

int BoardInfinityArray[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11};

Accessing Two-Dimensional Array Elements

The row position and column index of a two-dimensional array are used to access individual elements inside the array. For instance,

int val = a[2][3];

The above line will choose the fourth member from the array's third row. It is seen in the figure up top. Check out the program below, where we utilized nested loops to manage a two-dimensional array.

#include <stdio.h>

int main () {

  /* 2D Array - 5x2*/
  int BoardArray[5][2] = { {0,0}, {1,2}, {2,4}, {3,6},{4,8}};
  int i, j;

  /* Nested Loop is required to iterate over 2D arrays */
  for ( i = 0; i < 5; i=i+1 ) {
      for ( j = 0; j < 2; j=j+1 ) {
        printf("a[%d][%d] = %d\n", i,j, a[i][j] );
      }
  }
 
  return 0;
}


Output:
a[0][0]: 0
a[0][1]: 0
a[1][0]: 1
a[1][1]: 2
a[2][0]: 2
a[2][1]: 4
a[3][0]: 3
a[3][1]: 6
a[4][0]: 4
a[4][1]: 8

write your code here: Coding Playground

Arrays can have any number of dimensions, as was previously stated, but it is probable that the majority of the arrays you construct will only have one or two dimensions.

Summary

  1. You learned about the array data structure in this article. It is a collection of discrete components of comparable kinds that may be stored in a single location.
  2. A one-dimensional array keeps track of a single list of different elements with related data types.
  3. An array of 2D arrays makes up a three-dimensional array.
  4. Each kind of array may be initialized at the time of declaration, and we can then access any of its entries.