2 Dimensional Arrays

Back - C Language Notes By Vivek Sir email: vivekdubey22@gmail.com (w) 9826424484

C Language Video

·        Implementing a database of information as a collection of arrays can be inconvenient when many arrays are passed to utility functions to process the database.

·        It would be nice to have a single data structure which can hold all the information, and pass it all at once.

·        2-dimensional arrays provide most of this capability.

·        Like a 1D array, a 2D array is a collection of data cells, all of the same type, which can be given a single name.

·        However, a 2D array is organized as a matrix with a number of rows and columns.

How do we declare a 2D array?

·        Similar to the 1D array, the data type  are specified: the name, and the size of the array.

·        But the size of the array is described as the number of rows and number of columns.

·        For example:

     int a[MAX_ROWS][MAX_COLS];

·        This declares a data structure that looks like:

http://www-ee.eng.hawaii.edu/~tep/EE160/Notes/Array/Figs/2darray.gif

 

WAP to Read and Write 2 by 2 Matrix.

#include<stdio.h>

void main(){

   /* 2D array declaration*/

   int disp[2][2];

   /*Counter variables for the loop*/

   int i, j;

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

      for(j=0;j<2;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<2;j++) {

                printf("%d ", disp[i][j]);

            }

        printf("\n");

      }

   }

 }

 

Output

Enter value for disp[0][0]:10                                                                                                         

Enter value for disp[0][1]:20                                                                                                         

Enter value for disp[1][0]:30                                                                                                         

Enter value for disp[1][1]:40                                                                                                         

Two Dimensional array elements:                                                                                                        

10 20                                                                                                                                 

30 40 

 

Back - C Language Notes By Vivek Sir email: vivekdubey22@gmail.com (w) 9826424484

C Language Video