2D Arrays


Explanation

A two-dimensional array is an array that stores data in the form of rows and columns. It is also called a matrix. In C language, a 2D array is declared using two indexes, where the first index represents the row and the second index represents the column.

In this program, a 4 x 4 two-dimensional array is created. The user enters values into the array using nested for loops. After storing the values, another nested loop is used to display the complete matrix.

How It Works?

  • Step 1: Declare a two-dimensional array m[4][4] to store matrix values.
  • Step 2: Use nested for loops to accept values for rows and columns.
  • Step 3: Store each entered value at the specified row and column position.
  • Step 4: Use another nested for loop to display all array elements.
  • Step 5: Print a new line after displaying each row.

Example Program


#include <stdio.h>
#include <conio.h>

main()
{

    int m[4][4], k, p;

    clrscr();

    for(k = 0; k <= 3; k++)
    {

        for(p = 0; p <= 3; p++)
        {

            printf("\nEnter any no : ");

            scanf("%d", &m[k][p]);

        }

    }


    for(k = 0; k <= 3; k++)
    {

        for(p = 0; p <= 3; p++)
        {

            printf("%d ", m[k][p]);

        }

        printf("\n");

    }


    getch();

}

Output

Enter any no : 1
Enter any no : 2
Enter any no : 3
Enter any no : 4
Enter any no : 5
Enter any no : 6
Enter any no : 7
Enter any no : 8
Enter any no : 9
Enter any no : 10
Enter any no : 11
Enter any no : 12
Enter any no : 13
Enter any no : 14
Enter any no : 15
Enter any no : 16

1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16

Practice Exercises

Task 1: Write a C program to create a 3 x 3 two-dimensional array. Accept values from the user and display the complete matrix using nested for loops.

Goal: Learn how to store and display data using a two-dimensional array with rows and columns.

💡 Hint: Declare a 2D array using int m[3][3]. Use one for loop for rows and another for loop for columns to accept and display the values.
💡 Show Solution

#include <stdio.h>
#include <conio.h>

main()
{

    int m[3][3], k, p;

    clrscr();

    for(k = 0; k <= 2; k++)
    {

        for(p = 0; p <= 2; p++)
        {

            printf("\nEnter any no : ");

            scanf("%d", &m[k][p]);

        }

    }


    for(k = 0; k <= 2; k++)
    {

        for(p = 0; p <= 2; p++)
        {

            printf("%d ", m[k][p]);

        }

        printf("\n");

    }


    getch();

}

Output
Enter any no : 10
Enter any no : 20
Enter any no : 30
Enter any no : 40
Enter any no : 50
Enter any no : 60
Enter any no : 70
Enter any no : 80
Enter any no : 90

10 20 30
40 50 60
70 80 90
Explanation: The program creates a 3 x 3 two-dimensional array. The first nested for loop accepts values from the user and stores them in rows and columns. The second nested for loop displays all elements of the matrix in proper row and column format.