Skip to main content

Multi-dimensional Arrays in C

Introduction

In this tutorial, we will discuss one of the essential concepts in C programming, multi-dimensional arrays. We will start with the basics and gradually move towards more complex aspects.

What are Multi-dimensional Arrays?

In simple terms, a multi-dimensional array is an array of arrays. It is a collection of elements, each of which is an array itself. These arrays can be two-dimensional (2D), three-dimensional (3D), or even higher dimensional.

Declaring a Multi-dimensional Array

The general syntax for declaring a multi-dimensional array is as follows:

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

For instance, to declare a 2D array of integers, you could write:

int numbers[3][4];

Here, numbers is a 2D array that can hold 12 (3x4) integer values.

Initializing a Multi-dimensional Array

You can initialize a multi-dimensional array at the time of declaration. Here's how you can initialize a 2D array:

int numbers[3][4] = {
{0, 1, 2, 3} , /* initializers for row indexed by 0 */
{4, 5, 6, 7} , /* initializers for row indexed by 1 */
{8, 9, 10, 11} /* initializers for row indexed by 2 */
};

Accessing Elements of a Multi-dimensional Array

To access elements of a multi-dimensional array, you should specify the indices for each dimension. For example, to access the element at the first row and second column of a 2D array, you would write:

numbers[0][1];

Example: A 2D Array in Action

Here's a simple program that uses a 2D array:

#include <stdio.h>

int main () {

/* an array with 5 rows and 2 columns*/
int a[5][2] = { {0,0}, {1,2}, {2,4}, {3,6},{4,8}};
int i, j;

/* output each array element's value */
for ( i = 0; i < 5; i++ ) {
for ( j = 0; j < 2; j++ ) {
printf("a[%d][%d] = %d\n", i,j, a[i][j] );
}
}

return 0;
}

When you run the above program, it would produce the following result:

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

Summary

In this tutorial, we have introduced the concept of multi-dimensional arrays in C. We have discussed how to declare, initialize, and access elements in a multi-dimensional array. We hope this tutorial has given you a good understanding of this topic. Practice and experimentation are the keys to learning, so we encourage you to write your own programs using multi-dimensional arrays.