Two-dimensional arrays in C

An array is a collection of fixed number values of a single type. Hence, an integer array can only hold elements whose data type is also an integer.

A two-dimensional array in C can be thought of as a matrix with rows and columns. The general syntax used to declare a two-dimensional array is:

svg viewer

A two-dimensional array is an array of several one-dimensional arrays. Following is an array with five rows, each row has three columns:

int my_array[5][3];

The code above declares a one-dimensional array that has five elements. Each of these five elements is themselves, an array of three integers. The following diagram shows a simple way to visualize this:

svg viewer

Initializing two-dimensional a​rrays

A two-dimensional array can be initialized during its declaration.

#include <stdio.h>
int main()
{
int my_array[5][3] = {
{1, 2, 3}, //row 1
{4, 5, 6}, //row 2
{7, 8, 9}, //row 3
{10, 11, 12}, //row 4
{13, 14, 15} //row 5
};
}

The inside curly braces are optional, two-dimensional arrays can be declared with or without them.

#include <stdio.h>
int main()
{
int my_array[5][3] = {1, 2, 3, 4, 5, 6, 7, 8,
9, 10, 11, 12, 13, 14, 15};
}

Accessing elements in two-dimensional arrays

Just like one-dimensional arrays, two-dimensional arrays also require indices to access the required elements. A row and a column index are needed to access a particular element; for nested loops, two indices (one to traverse the rows and the other to traverse the columns in each row) are required to print a two-dimensional array.

#include <stdio.h>
int main()
{
// array declaration and initialization
int my_array[5][3] = {
{1, 2, 3}, //row 1
{4, 5, 6}, //row 2
{7, 8, 9}, //row 3
{10, 11, 12}, //row 4
{13, 14, 15} //row 5
};
// accessing and printing the elements
for ( int i = 0; i < 5; i++ ) {
// variable i traverses the rows
for ( int j = 0; j < 3; j++ ) {
// variable j traverses the columns
printf("my_array [%d][%d] = %d\n", i,j, my_array[i][j] );
}
}
return 0;
}

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved