Categories: C

Two-dimensional array

The two-dimensional array can be defined as an array of arrays. The 2D array is organized as matrices, which can be represented as the collection of rows and columns. However, 2D arrays are created to implement a relational database lookalike data structure. It provides ease of holding the bulk of data at once, which can be passed to any number of functions wherever required.

The syntax for declaring a 2D array is shown below.
array name[rows][columns] data type;

Consider the following scenario:

int arr[4][3]; 

Here, 4 represents the number of rows and 3 represents the number of columns.

Note: If the declaration and initialization of the 1D array are done concurrently, we don’t need to mention the array size. This, however, will not work with 2D arrays. We must define at least the array’s second dimension.

storing elements in a matrix and printing them:
#include <stdio.h>    
void main ()    
{    
    int z[4][3],i,j;     
    for (i=0;i<4;i++)    
    {    
        for (j=0;j<3;j++)    
        {    
            printf("Enter z[%d][%d]: ",i,j);                
            scanf("%d",&z[i][j]);    
        }    
    }    
    printf("\n printing the elements ....\n");     
    for(i=0;i<4;i++)    
    {    
        printf("\n");    
        for (j=0;j<3;j++)    
        {    
            printf("%d\t",z[i][j]);    
        }    
    }    
} 
Output:
Enter z[0][0] = 1
Enter z[0][1] = 2
Enter z[0][2] = 3
Enter z[1][0] = 2
Enter z[1][1] = 3
Enter z[1][2] = 4
Enter z[2][0] = 3
Enter z[2][1] = 4
Enter z[2][2] = 5
Enter z[3][0] = 4
Enter z[3][1] = 5
Enter z[3][2] = 6

printing the elements ....
1 2 3
2 3 4
3 4 5
4 5 6

We’ve made a two-dimensional array of size[4][3], thus the data is stored in a matrix format, where 4 is the number of rows and 3 is the number of columns.

Similarly, we create other multidimensional arrays.

Note: also read about the Passing arguments between functions in C & Arrays in C

Follow Me

If you like my post please follow me to read my latest post on programming and technology.

https://www.instagram.com/coderz.py/

https://www.facebook.com/coderz.py

Share
Published by
Rabecca Fatima

Recent Posts

Efficient Order Log Storage

You manage an e-commerce website and need to keep track of the last N order…

2 weeks ago

Select a Random Element from a Stream

You are given a stream of elements that is too large to fit into memory.…

2 weeks ago

Estimate π Using Monte Carlo Method

The formula for the area of a circle is given by πr². Use the Monte…

1 month ago

Longest Substring with K Distinct Characters

Given an integer k and a string s, write a function to determine the length…

1 month ago

Staircase Climbing Ways

There is a staircase with N steps, and you can ascend either 1 step or…

1 month ago

Autocomplete System Implementation

Build an autocomplete system that, given a query string s and a set of possible…

1 month ago