C

Example Of Two-Dimensional (2D) Arrays In C Programming

A 2D array is an array of arrays. In C programming, a two-dimensional (2D) array is also known as a matrix. A matrix can be visualized as a table with rows and columns.
Before we get into more detail about two-dimensional arrays, let’s look at the following C program.

Example of a Simple Two Dimensional (2D) Array

This program shows how to store user-entered elements in a two-dimensional array and how to display the elements of a two-dimensional array. Don’t worry about the initialization of the two-dimensional array shown in this example for the time being; we’ll go over that later.

#include<stdio.h>
int main(){
   /* 2D array declaration*/
   int disp[2][3];
   /*Counter variables for the loop*/
   int i, j;
   for(i=0; i<2; i++) {
      for(j=0;j<3;j++) {
         printf("Enter value for disp[%d][%d]:", i, j);
         scanf("%d", &disp[i][j]);
      }
   }
   //Displaying array elements
   printf("Two Dimensional array elements:\n");
   for(i=0; i<2; i++) {
      for(j=0;j<3;j++) {
         printf("%d ", disp[i][j]);
         if(j==2){
            printf("\n");
         }
      }
   }
   return 0;
}

Output:

Enter value for disp[0][0]:1
Enter value for disp[0][1]:2
Enter value for disp[0][2]:3
Enter value for disp[1][0]:4
Enter value for disp[1][1]:5
Enter value for disp[1][2]:6
Two Dimensional array elements:
1 2 3 
4 5 6

2D Array Initialization

During declaration, there are two ways to initialize a two Dimensional array.

int disp[2][4] = {
    {10, 11, 12, 13},
    {14, 15, 16, 17}
};

OR

int disp[2][4] = { 10, 11, 12, 13, 14, 15, 16, 17};

Although both of the above declarations are valid, I recommend using the first method because it is more readable because it allows you to visualize the rows and columns of a 2d array.

Things to think about when setting up a 2D array

We already know that when we initialize a normal array (or one-dimensional array) during declaration, we do not need to specify its size. In the case of a 2D array, however, you must always specify the second dimension, even if you are specifying elements during the declaration. Let’s break this down with a few examples –

/* Valid declaration*/
int abc[2][2] = {1, 2, 3 ,4 }  
/* Valid declaration*/ 
int abc[][2] = {1, 2, 3 ,4 }  
/* Invalid declaration – you must specify second dimension*/
int abc[][] = {1, 2, 3 ,4 }   
/* Invalid because of the same reason  mentioned above*/
int abc[2][] = {1, 2, 3 ,4 }

How do I save user input data in a 2D array?

Using the following formula, we can determine how many elements a two-dimensional array can have: Arr[n1][n2] can contain n1*n2 elements. The dimensions of the array in the following example are 5 and 4. These measurements are referred to as subscripts. As a result, the first subscript value in this array is 5 and the second subscript value is 4.
As a result, the array abc[5][4] can contain 5*4 = 20 elements.
To store the elements entered by the user, we use two for loops, one of which is nested. The outer loop runs from 0 to (first subscript -1) and the inner for loop runs from 0 to (first subscript -1). (second subscript -1). This way, the elements would be entered in the following order: abc[0][0], abc[0][1], abc[0][2]. so on.

#include<stdio.h>
int main(){
   /* 2D array declaration*/
   int abc[5][4];
   /*Counter variables for the loop*/
   int i, j;
   for(i=0; i<5; i++) {
      for(j=0;j<4;j++) {
         printf("Enter value for abc[%d][%d]:", i, j);
         scanf("%d", &abc[i][j]);
      }
   }
   return 0;
}

2D arrays and pointers

As we know, the name of a one-dimensional array serves as a pointer to the array’s base element (first element). However, the logic for 2D arrays is slightly different. A 2D array can be thought of as a collection of several one-dimensional arrays.
As a result, abc[0] would contain the address of the first element of the first row (if we consider the above diagram number 1).
Similarly, abc[1] contains the address of the first element in the second row. To better understand it, let’s write a C program –

#include <stdio.h>
int main()
{
   int abc[5][4] ={
            {0,1,2,3},
            {4,5,6,7},
            {8,9,10,11},
            {12,13,14,15},
            {16,17,18,19}
            };
    for (int i=0; i<=4; i++)
    {
        /* The correct way of displaying an address would be
         * printf("%p ",abc[i]); but for the demonstration
         * purpose I am displaying the address in int so that
         * you can relate the output with the diagram above that
         * shows how many bytes an int element uses and how they
         * are stored in contiguous memory locations.
         *
         */
    	printf("%d ",abc[i]);
    }
    return 0;
}

Output:

1600101376 1600101392 1600101408 1600101424 1600101440

As mentioned in the comments, the actual address representation should be in hex, for which we use%p instead of%d. This is simply to demonstrate that the elements are stored in adjacent memory locations. You can see from the output and the diagram above that the difference between these addresses is the number of bytes consumed by the row’s elements.
The addresses displayed in the output correspond to the first element of each row, abc[0][0], abc[1][0], abc[2][0], abc[3][0], and abc[4][0].

How do I find the address of a 2D array element?

There are two methods for determining the address of a 2D array element:
1. Major Row Order
2. Major Column Order

1. Major Row Order

If an array is represented by arr[x][y], then the address of a random element arr[i][j] can be calculated as follows:

Address of arr[i][j] = Base Address + (i * y + j) * size

The address of element arr[0][0] is represented by Base Address (the first element of the array).
Given an array, arr[10][25], with a base address of 100 and an element size of 4 Bytes in memory. Find the address of arr[8][6] using row-major order?

Address of arr[8][6] = Base Address + (8*25 + 6)*4
                     = 100 + (200+6)*4
                     = 100+824 = 924

2. Major Column Order

If an array is represented by arr[x][y], where x represents the rows and y represents the columns, the address of a random element arr[i][j] can be calculated using the column major method as follows:

Address of arr[i][j] = Base Address + (j * x + i) * size

Example: Given an array, arr[20][20], with a base address of 100 and an element size of 4 bytes in memory. Find the address of arr[5][16] using column-major order?

Address of arr[5][16] = Base Address + (j * x + i) * size
                     = 100 + (16*20+ 5)*4
                     = 100+ 325*4
                     = 100+ 1300 = 1400

Related Articles

Leave a Reply

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

Back to top button