top

Search

C Tutorial

.

UpGrad

C Tutorial

Two Dimensional Array in C

An array’s dimension represents a specific direction in which the array elements can be manipulated. In C, an array with two dimensions is called a two dimensional array.

Let’s dive in to explore more about two dimensional arrays and their accurate implementation through various examples. 

Definition of Two Dimensional Array

A two dimensional array in C is an array of multiple one-dimensional arrays. It holds an array of different arrays, an array of different one-dimensional arrays, and a list of different lists. It is represented as a matrix comprising rows and columns or an array of arrays.

 Importance of Two Dimensional Array in programming

-Two dimensional array in C help you to store and work on data in a tabular format.

-They are useful for representing matrices, tables, grids, or other tabular data structures.

-They are stored in contiguous memory locations. So, they facilitate efficient memory utilisation.

Declaration and Initialization of Two Dimensional Array in C

Syntax for declaring Two Dimensional Array

Here’s the syntax for declaring a two dimensional array in C:

data_type array_name[i][j]

Here, i and j represent the size of the two dimensions; i shows the number of rows and j shows the number of columns.

Here’s an example of a two dimensional array:

int X[5][7];

The above command declares a two-dimensional array named X with 5 rows and 7 columns.

Example of Initializing Two Dimensional Array

You can initialize a two dimensional array in C in one of the below two ways:

Method-1: Initializing without nested braces:

The syntax for this method is:

int Ar[x][y] = {element 1, element 2, ... element xy}

Based on the above syntax, here’s the two-dimensional array example:

int Ar[2][3] = {2, 3, 5, 7, 8, 9}

Method-2: Initializing with nested braces:

The syntax for this method is:

int Ar[x][y] = {{ element 1, element 2, .. element y} , {......} , {..., element xy-1, element xy}};

Example:

int Ar[2][3] = {{5, 2, 3}, {7, 9, 8}};

Explanation of how memory is allocated for Two Dimensional Array

The memory for a two-dimensional array in C is assigned in an adjacent block. The concept it uses for the same is “row-major order”.

The following section shows how the memory is allocated for an int array[3][4].

arr[0][0] arr[0][1] arr[0][2] arr[0][3]
arr[1][0] arr[1][1] arr[1][2] arr[1][3]
arr[2][0] arr[2][1] arr[2][2] arr[2][3]

Accessing Elements of Two Dimensional Array

Syntax for accessing elements of Two Dimensional Array 

Here’s the two dimensional array syntax for accessing elements.

array_name[i][j]

Examples of accessing Two Dimensional Array elements

In the given example, if you have an array X[10][20], and you want to access the element in the 5th column and 4th row, the correct syntax would be X[3][4].

Since C uses zero-based indexing, the 4th row corresponds to index 3, and the 5th column corresponds to index 4.

Therefore, the correct syntax for accessing the element at the 4th row and 5th column in a two-dimensional array named X would be X[3][4].

Explanation of how Two Dimensional Arrays are stored in memory

Operations on Two Dimensional Array

Addition and Subtraction of Two Dimensional Arrays

You must iterate on the elements of an array and implement the addition and subtraction operations to perform the addition and subtraction of a two dimensional array in C. The following example shows addition and subtraction of two dimensional arrays:

#include <stdio.h>

#define ROWS 3
#define COLUMNS 3

void addArrays(int ar1[][COLUMNS], int ar2[][COLUMNS], int res[][COLUMNS]) {
for (int a = 0; a < ROWS; a++)
{
for (int b = 0; b < COLUMNS; b++)
{
res[a][b] = ar1[a][b] + ar2[a][b];
}
}
}

void subtractArrays(int ar1[][COLUMNS], int ar2[][COLUMNS], int res[][COLUMNS]) {
for (int a = 0; a < ROWS; a++)
{
for (int b = 0; b < COLUMNS; b++)
{
res[a][b] = ar1[a][b] - ar2[a][b];
}
}
}

void displayArray(int ar[][COLUMNS]) {
for (int a = 0; a < ROWS; a++) {
for (int b = 0; b < COLUMNS; b++) {
printf("%d\t", ar[a][b]);
}
printf("\n");
}
printf("\n");
}

int main() {
int ar1[ROWS][COLUMNS] = {{4, 5, 6}, {1, 4, 5}, {2, 8, 9}};
int ar2[ROWS][COLUMNS] = {{7, 8, 5}, {6, 4, 5}, {4, 3, 1}};
int res[ROWS][COLUMNS];

printf("Array-1:\n");
displayArray(ar1);

printf("Array-2:\n");
displayArray(ar2);

addArrays(ar1, ar2, res);
printf("The addition of arrays is:\n");
displayArray(res);

subtractArrays(ar1, ar2, res);
printf("The subtraction of arrays is:\n");
displayArray(res);

return 0;
}

Output:

Array-1:
456
145
289

Array-2:
785
645
431

The addition of arrays is:
111311
7810
61110

The subtraction of arrays is:
-3-31
-500
-258

Multiplication of Two Dimensional Arrays

If you want to multiply a two dimensional array in C, you must iterate over the arrays’ elements and implement the necessary arithmetic operations. Let’s look at the following example.

#include <stdio.h>

#define ROWS1 2
#define COLUMNS1_ROWS2 3
#define COLUMNS2 2

void multiplyArrays(int arr1[][COLUMNS1_ROWS2], int arr2[][COLUMNS2], int result[][COLUMNS2])
{
for (int i = 0; i < ROWS1; i++)
{
for (int j = 0; j < COLUMNS2; j++)
{
result[i][j] = 0;
for (int z = 0; z < COLUMNS1_ROWS2; z++)
{
result[i][j] += arr1[i][z] * arr2[z][j];
}
}
}
}

void displayArray(int arr[][COLUMNS2], int rows)
{
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < COLUMNS2; j++)
{
printf("%d\t", arr[i][j]);
}
printf("\n");
}
printf("\n");
}

int main()
{
int arr1[ROWS1][COLUMNS1_ROWS2] = {{1, 2, 3}, {4, 5, 6}};
int arr2[COLUMNS1_ROWS2][COLUMNS2] = {{7, 8}, {9, 10}, {11, 12}};
int result[ROWS1][COLUMNS2];

printf("Array-1:\n");
displayArray(arr1, ROWS1);

printf("Array-2:\n");
displayArray(arr2, COLUMNS1_ROWS2);

multiplyArrays(arr1, arr2, result);
printf("Multiplication of arrays is:\n");
displayArray(result, ROWS1);

return 0;
}

Output:

Array-1:
12
34

Array-2:
78
910
1112

Multiplication of arrays is:
5864
139154

Transpose of Two Dimensional Array

You must interchange the columns and rows of the array if you want to determine the transpose of a two dimensional array in C.

Passing Two Dimensional Array to Function

Syntax for passing Two Dimensional Array to Function

void functionName(dataType arrayName[][numCols], int numRows) {
// Function body
}

Here, dataType represents the data type of the elements defined in the array, ArrayName represents the array’s name, and NumCols represents the number of columns in a particular array.

 Example of passing Two Dimensional Array to Function

#include <stdio.h>

// The following function prints a 2D array
void printArray(int arry[][3], int rows, int columns)
{
int m, n;

for (m = 0; m < rows; m++)
{
for (n = 0; n < columns; n++)
{
printf("%d ", arry[m][n]);
}
printf("\n");
}
}

int main()
{
int array[2][3] =
{
{1, 5, 9},
{2, 8, 3}
};

// Pasess the array to the function
printArray(array, 2, 3);

return 0;
}

Output:

1 5 9
2 8 3

In the above example, we define a function printArray that accepts a two-dimensional array. It accepts the number of rows and columns as parameters. We use nested loops in the function to traverse the array and display its elements.

Explanation of how Two Dimensional Array is passed to Function

You can pass a two dimensional array to a function by mentioning the array dimensions within the function parameter declaration.

Dynamic Memory Allocation of Two Dimensional Array

In C, you can use the malloc function and pointers to dynamically allocate memory for a two dimensional array.

Syntax for dynamically allocating memory for Two Dimensional Array

datatype **arrayname;
arrayname = ( datatype **)malloc(numrows * sizeof(datatype *));
for (int i = 0; i < numrows; i++) {
arrayname[i] = ( datatype *)malloc(numcols * sizeof(datatype));
}

Example of dynamically allocating memory for Two Dimensional Array

#include <stdio.h>
#include <stdlib.h>

int main() 
{
int numrows = 2;
int numcols = 3;

int **ar;
ar = (int **)malloc(numrows * sizeof(int *));
for (int x = 0; x < numrows; x++) 
{
ar[x] = (int *)malloc(numcols * sizeof(int));
}

for (int x = 0; x < numrows; x++) 
{
for (int y = 0; y < numcols; y++) 
{
ar[x][y] = x * numcols + y + 1;
}
}

for (int x = 0; x < numrows; x++) 
{
for (int y = 0; y < numcols; y++) 
{
printf("%d\t", ar[x][y]);
}
printf("\n");
}

for (int x = 0; x < numrows; x++) {
free(ar[x]);
}
free(ar);

return 0;
}

Output:

123
456

Explanation of how to free the memory allocated for Two Dimensional Array

If you want to free the memory allocated for any two dimensional array in C, you must separately deallocate memory for each row and then free the memory for the array.

Multidimensional Array

Definition of Multidimensional Array

A multidimensional array in C is an array comprising multiple dimensions. It is essentially an array of arrays.

dataType arrayname[size1][size2]...[sizeN];

Example of Three Dimensional Array

#include <stdio.h>

#define S1 2
#define S2 3
#define S3 4

int main() 
{
int arr[S1][S2][S3];

// Assigns values to the array
for (int a = 0; a < S1; a++) {
for (int b = 0; b < S2; b++) {
for (int c = 0; c < S3; c++) {
arr[a][b][c] = (a * S2 * S3) + (b * S3) + c + 1;
}
}
}

// Displays the array
for (int a = 0; a < S1; a++) {
for (int b = 0; b < S2; b++) {
for (int c = 0; c < S3; c++) {
printf("%d\t", arr[a][b][c]);
}
printf("\n");
}
printf("\n");
}

return 0;
}

Output:

1234
5678
9101112

13141516
17181920
21222324

The above example defines a three-dimensional array arr with dimensions S1, S2, and S3. These dimensions are 2, 3, and 4, respectively. We use nested loops to assign values to the array’s elements. The output displays the array after iterating on each dimension through nested loops.

Explanation of how to access elements of Multidimensional Array

To access a multidimensional array’s elements in C, you need to use multiple sets of square brackets to declare each dimension’s indices.

Best Practices

Tips for using Two Dimensional Array effectively and safely

-Thoroughly determine the number of columns and rows in an array. It helps you to correctly allocate memory, iterate over the array, and access elements.

-Before using an array, always initialize it with proper values.

-Make sure the indices you use fall in the valid range of the array.

Common mistakes to avoid

-Don’t access the elements outside the acceptable range of the array.

-If you are dynamically allocating memory for your two dimensional array using malloc, make sure to correctly allocate memory for both the columns and rows.

-Use the proper data type for your array’s elements depending on the data to be sorted.

Conclusion

This tutorial familiarises you with definition, declaration, operations, and many other aspects of two dimensional array in C. For several reasons, It is essential to understand two dimensional arrays in C programming. These include the ease of accessing and processing data, effectively handling multidimensional data structures, representing and manipulating grid-like data structures, etc.

Learning through tutorials is one of the most effective ways to strengthen your C fundamentals. You can pursue upGrad’s Full Stack Software Development Bootcamp, which imparts the necessary skills to stay competitive in the tech industry.

Enroll now to commence your journey!

FAQs

1. Can a two dimensional array have different row sizes in C?

No, a two dimensional array in C should have a fixed number of rows and columns. Each row should have the same number of columns. You can’t declare a two dimensional array with different row sizes.

2. Can you loop through a two dimensional array in C?

Yes, you can loop through a two-dimensional array with the help of nested loops. The external loop iterates over the rows whereas the inner loop iterates over the columns.

3. Are two dimensional arrays stored in column-major or row-major order in memory?

The two dimensional arrays are stored in row-major order in memory in C. It implies that a row’s elements are consecutively stored in memory, followed by the next row’s elements, and so on. This sequence enhances cache utilisation and makes memory access more efficient.

Leave a Reply

Your email address will not be published. Required fields are marked *