Two Dimensional Arrays

http://install4install.com

Whether it be playing a tic tac toe game(Fig 3) , storing data in a spreadsheet(Fig 2) or a Rating chart of movie by reviewers(Fig 1), a single dimensional or 1D array cannot store the data. Instead, it needs to be stored in 2 dimensional or multi-dimensional array.

Fig 3 : Tic Tac Toe Game(2D Array)

Fig 3 : Tic Tac Toe Game(2D Array) [1]

Fig 2 : Spreadsheet

Fig 2 : Spreadsheet [2]

Fig 3 : Movie Review Chart

Fig 1 : Movie Review Chart [3]

 

Types of Arrays

Two Dimensional Array

In a 2D array,the data is stored in form of a table i.e in form of rows and columns. The data is specified using indices/subscripts(locations of array). The first index refers to row and other refers to column.

Syntax to declare a 2D Array

data_type  array_name[size_row][size_column]; Example: If I want to store marks of 2 subjects 0f 3 different students, I can use a 2D array and will declare according to the following syntax. int marks[2][3]; Illustration

Consider the example shown in figure 4 that stores data of 3 students in English and Physics in a 2D array.

Fig 4 : A Two Dimensional Array

Fig 4 : A Two Dimensional Array

Here,

Initialization of 2D Array

data_type   name_array [size_row][size_column] = {values}; Program Example

#include<stdio.h>

int main()
{
int val[2][3] = {10,20,30,40,50,60};//or int val[2][3] = {(10,20,30),(40,50,60)}:
int i,j;
printf("The values of 2D Array are ");
for(i=0;i<2;i++)
{
printf("\n");
for(j=0;j<3;j++)
printf("%d \t",val[i][j]);
}
return 0;
}

Run Illustration

1. Initial value of i = 0.There are two rows of array so the upper bound of i taken as 2. 2.Nested for loop is used for the columns.Initial value of j is set to 0.There are 3 columns of array so the upper bound of j is taken as 3.

Fig 5 : Explanation of above program

Fig 5 : Explanation of above program

Initialization of 2 D Array through user input:

#include<stdio.h>

int main()
{
   int val[2][3];
   int i,j;
   printf("The values of 2D Array" are);
   for(i=0;i<2;i++)
    {
    for(j=0;j<3;j++)
    scanf("%d",&val[i][j]);
    }
   for(i=0;i<2;i++)
    {
    printf("\n");
    for(j=0;j<3;j++)
    printf("%d \t",val[i][j]);
    }
return 0;
}

Run This program has the same working like previous program except that the values are initialized from user through scanf. Two for loops are used separately for scanf function in order to take all the values from the user  first and then all the values are printed through printf function which is placed in another two for loops. If we will use scanf and prinf in the same for loops then output will be generated one by one as  the input is given to the system.



Short URL: http://tinyit.cc/480b99
Author: Cusp2207 on March 18, 2014
Category: Computer Science, Data Structures
Tags:

Leave a Reply

Last articles