Two Dimensional Array In C Language

Array Definition

Arrays are the derived data type and it can store the primitive type of data such as int, char, double, float, etc. But you can't store different types in a single array.

Arrays are a way to store a list of items. Each slot of the array holds an individual element, and you can place elements into or change the contents or those slots as you need to.

2-D Array Definition

C as a language provides for arrays of arbitrary dimensions. A two dimensional array of size m rows by n columns is declared.

2-D Array Declaration

We can declare an array in C using subscript operator.

 data_type array_name[rows][columns]; 

Elements in a two dimensional array can be accessed by means of a row and column. The row subscript generally is specified before the column subscript. Fore example, twodim[1][3]; will access the element in row number 1(the second row) and in a column number 3 (fourth) f the array.

2-D Array Initialization

  //4 rows 3 column
  int arr[4][3]={{1,2,3},{3,4,5},{6,7,8},{9,0,1}};  

  //2 rows 3 column
  int arr[2][3]={{1,2,3},{4,5,6}};

2-D other way of Initialization

The values can also be initialized by forming groups of initial values enclosed within braces. The values within an inner pair of braces will be assigned to the elements of a row.

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

Note: While Initializing a two dimensional array it is necessary to mention the second (column) dimension, wherease the first dimension (row) is optional. Thus the declarations given below are perfectly acceptable.

 int arr[2][3]={12,13,24,23,41,14};

Example 1:


 value of arr[0] [0] is 10
 value of arr[0] [1] is 20
 value of arr[1] [0] is 30
 value of arr[1] [1] is 40

Example 2: Storing elements in a matrix and printing it.


Enter number of rows of the matrix: 2
Enter number of columns of the matrix: 3
Enter 6 elements of the matrix:
Elements of the matrix you have entered are:
1       2       3

4       5       6