Programming in C: Unit II (a): Arrays

Two-Dimensional Arrays

with Example C Programs

Till now we have read only about one-dimensional arrays. A one-dimensional array is organized linearly and only in one direction. But at times, we need to store data in the form of matrices or tables.

TWO-DIMENSIONAL ARRAYS

Till now we have read only about one-dimensional arrays. A one-dimensional array is organized linearly and only in one direction. But at times, we need to store data in the form of matrices or tables. Here the concept of one-dimensional array is extended to incorporate two-dimensional data structures. A two-dimensional array is specified using two subscripts where one subscript denotes row and the other denotes column. C considers the two-dimensional array as an array of one-dimensional arrays. Figure 5.25 shows a two-dimensional array which can be viewed as an array of arrays.

Declaring Two-dimensional Arrays

Similar to one-dimensional arrays, two-dimensional arrays must be declared before being used. The declaration statement tells the compiler the name of the array, the data type of each element in the array, and the size of each dimension. A two-dimensional array is declared as

data_type array_name [row_size] [column_size];

Therefore, a two-dimensional m n array is an array that contains m x n data elements and each element is accessed using two subscripts, i and j where i<= m and j<= n.

For example, if we want to store the marks obtained by 3 students in 5 different subjects, then we can declare a two-dimensional array as

int marks [3] [5];

A two-dimensional array called marks is declared that has m (3) rows and n (5) columns. The first element of the array is denoted by marks [0] [0], the second element as marks [0] [1], and so on. Here, marks [0] [0] stores the marks obtained by the first student in the first subject, marks [1] [0] stores the marks obtained by the second student in the first subject, and so on.

Note

Each dimension of the two-dimensional array is indexed from zero to its maximum size minus one. The first index selects the row and the second selects the column.

The pictorial form of a two-dimensional array is given in Figure 5.26.


Hence, we see that a 2D array is treated as a collection of ID arrays. To understand this, we can also see the representation of a two-dimensional array as shown in Figure 5.27.

Although Figure 5.27 shows a rectangular picture of a two-dimensional array, these elements will be actually stored sequentially in memory. Since computer memory is basically one-dimensional, a multidimensional array cannot be stored in memory as a grid.

There are two ways of storing a two-dimensional array in memory. The first way is row major order and the second is column major order. Let us see how the elements of a 2D array are stored in row major order. Here, the elements of the first row are stored before the elements of the second and third row, i.e., the elements of the array are stored row by row where n elements of the first row will occupy the first n locations. This is illustrated in Figure 5.28.

When we store the elements in a column major order, the elements of the first column are stored before the elements of the second and third column, i.e., the elements of the array are stored column by column where m elements of the first column will occupy the first m locations. This is illustrated in Figure 5.29.

In one-dimensional arrays, we have seen that computer does not keep track of the address of every element in the array. It stores only the address of the first element and calculates the addresses of other elements from the base address (address of the first element). Same is the case with a two-dimensional array. Here also, the computer stores the base address and the address of the other elements is calculated using the following formula.

Address (A[I] [J] ) = B_A + w{M(J - 1) + (I - 1)}, if the array elements are stored in column major order, and

Address (A[I] [J]) = B_A + w{N (I - 1) + (J - 1)}, if the array elements are stored in row major order.loo where, w is the word size, i. e., number of bytes required to store element, M is the number of rows, N is the number of columns, I and J are the subscripts of the array element, and B_A is the base address.

Example 5.7

Consider  a 20 × 5 two-dimensional array Marks which has base address = 1000 and the word size = 2. Now compute the address of the element Marks [18, 4] assuming that the elements are stored in row major order.

Address (A[I] [J])

= Base_Address + w{N (I - 1) + (J - 1)}

Address (Marks [18,4])

= 1000 + 2{5 (18 − 2{5 (18- 1) + (4 - 1) }

 = 1000 + 2 { 5 (17) + 3}

= 1000 + 2 (88)

= 1000 + 176 = 1176

Initializing Two-dimensional Arrays

Like in case of other variables, declaring a two- dimensional array only reserves space for the array in the memory. No values are stored in it. A two-dimensional array is initialized in the same way as a one-dimensional array. For example,

int marks [2] [3] {90, 87, 78, 68, 62, 71};

The initialization of a two-dimensional array is done row by row. The above statement can also be written as

int marks [2] [3]={{90, 87, 78}, {68, 62, 71}};

The given two-dimensional array has 2 rows and 3 columns. Here, the elements in the first row are initialized first and then the elements of the second row are initialized. Therefore,

marks [0] [0] = 90  marks [0] [1] = 87

marks [0] [2] = 78  marks [1] [0] = 68

marks [1] [1] = 62  marks [1] [2] = 71

Therefore, in the above example, each row is defined as a one-dimensional array of three elements that are enclosed in braces. Commas are used to separate the elements in the row as well as to separate the elements of two rows.

In case of one-dimensional arrays, if the array is completely initialized, we may omit the size of the array. Same concept can be applied to a two-dimensional array, except that only the size of the first dimension can be omitted. Therefore, the declaration statement given below is valid.

int marks [] [3]={{90, 87, 78}, {68, 62, 71}};

In order to initialize the entire two-dimensional array to zero, simply specify the first value as zero, i.e., simply write

int marks [2] [3] = {0};

If some values are missing in the initializer then it is automatically set to zero. For example, the statement given below will initialize the values in the first row but the elements of the second row will be initialized to zero.

int marks [2] [3] ={ {50, 60, 70}};

Individual elements of a two-dimensional array can be initialized using the assignment operator as shown below.

marks [1] [2] = 79;

marks [1] [2] = marks [1] [1] + 10;

In order to input the values from the keyboard, you must use the following code.

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

for(j=0;j<2;j++)

scanf("%d", &arr[i] [j]);

Note

An un-initialized array contains unpredictable contents.

Accessing the Elements of Two-dimensional Arrays

The elements of a 2D array are stored in contiguous memory locations. While accessing the elements, remember that the last subscript varies most rapidly whereas the first varies least rapidly.

In case of one-dimensional arrays we used a single for loop to vary the index i in every pass, so that all the elements could be scanned. Since a two-dimensional array contains two subscripts, we will use two for loops to scan the elements. The first for loop will scan each row in the 2D array and the second for loop will scan individual columns for every row in the array.

Look at the programs given below which use two for loops to access the elements of a 2D array.

22. Write a program to print the elements of a 2D array.

#include <stdio.h>

#include <conio.h>

int main()

{

int arr [2] [2] = {12, 34, 56,32};

int i, j;

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

{

printf("\n");

for(j=0;j<2;j++)

printf("%d\t", arr[i][j]);

}

return 0;

}

Output

12 34

56 32

23. Write a program to generate Pascal's triangle.

#include <stdio.h>

#include <conio.h>

int main()

{

int arr [7] [7]={0};

int row=2, col, i, j;

arr [0] [0] = arr [1] [0] = arr[1] [1] = 1;

while (row < 7)

{

arr [row] [0] = 1;

for (col = 1; col <= row; col++)

arr [row] [col] = arr [row-1] [col-1] + arr [row-1] [col];

row++;

}

for (i=0;I < 7; i++)

{

printf("\n");

for(j=0;j<=i;j++)

printf("\t %d", arr[i] [j]);

}

getch();

return 0;

}

Output

1

1 1

1 2 1

1 3 3 1

1 4 6 4 1

1 5 10 10 5 1

1 6 15 20 15 6 1

24. In a small company there are 5 salesmen. Each salesman is supposed to sell 3 products. Write a program using two-dimensional array to print (i) the total sales by each salesman and (ii) total sales of each item.

#include <stdio.h>

#include <conio.h>

int main()

{

int sales [5] [3], i, j, total_sales=0; //INPUT DATA

printf("\n ENTER THE DATA");

printf("\n *********");

for (i=0;i<5; i++)

{

printf("\n Enter the sales of 3 items sold by salesman %d: ", i);

for(j=0;j<3;j++)

scanf("%d", &sales [i] [j]);

}

// PRINT TOTAL SALES BY EACH SALESMAN

for (i=0;i<5; i++)

{

total_sales = 0;

for(j=0;j<3;j++)

total_sales += sales [i][j];

printf("\n Total Sales By Salesman %d %d", i, total_sales);

}

// TOTAL SALES OF EACH ITEM

for (i=0;i<3; i++) // for each item

{

total_sales=0;

for(j=0;j<5;j++) // for each salesman

total_sales += sales [j] [i];

printf("\n Total sales of item %d %d", i, total_sales);

}

getch();

return 0;

}

Output

ENTER THE DATA

*********************

Enter the sales of 3 items sold by saleman 0: 23 23 45

Enter the sales of 3 items sold by salesman 1: 34 45 63

Enter the sales of 3 items sold by salesman 2: 36 33 43

Enter the sales of 3 items sold by salesman 3: 33 52 35

Enter the sales of 3 items sold by salesman 4: 32 45 64

Total Sales By Salesman 0 = 91

Total Sales By Salesman 1 = 142

Total Sales By Salesman 2 = 112

Total Sales By Salesman 3 = 120

Total Sales By Salesman 4 = 141

Total sales of item 0 = 158

Total sales of item 1 = 198

Total sales of item 2 = 250

25. In a class there are 10 students. Each student is supposed to appear in 3 tests. Write a program using two-dimensional arrays to print

(i) the marks obtained by each student in different subjects.

(ii) total marks and average obtained by each student.

(iii) store the average of each student in a separate 1D array so that it can be used to calculate the class average.

#include <stdio.h>

#include <conio.h>

int main()

{

int marks [10] [3], i, j;

int total_marks [10]={0};

float class_avg = 0.0, total_avg = 0.0;

float avg [10]; //INPUT DATA

printf("\n ENTER THE DATA");

for (i=0;i<10; i++)

{

printf("\n Enter the marks of student %d in 3 subjects : ", i);

for(j=0;j<3;j++)

scanf("%d", &marks [i] [j]);

}

// CALCULATE TOTAL MARKS OF EACH STUDENT

for (i=0;i<10; i++)

{

for(j=0;j<3;j++)

total_marks [i] += marks [i] [j];

}

// CALCULATE AVERAGE OF EACH STUDENT

for (i=0;i<10;i++)

{

for(j=0;j<3;j++)

avg [i] = (float) total_marks [i]/3.0;

}

// CALCULATE CLASS AVERAGE

for (i=0;i<10;i++)

total_avg += avg[i];

class_avg = (float) total_avg/10;

// DISPLAY RESULTS

printf("\n\n STUD NO.\t MARKS IN 3 SUBJECTS \t TOTAL MARKS \t AVERAGE");

for (i=0;i<10;i++)

{

printf("\n %4d", i);

for (j=0;j<3;j++)

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

printf("%4d \t%.2f", total_marks [i], avg [i]);

}

printf("\n\n CLASS AVERAGE %.2f", doss class_avg);

getch();

return 0;

}

Output

ENTER THE DATA

Enter the marks of student 0 in 3 subjects: 78 89 90

Enter the marks of student 1 in 3 subjects: 98 87 76

Enter the marks of student 2 in 3 subjects: 67 78 89

Enter the marks of student 3 in 3 subjects: 90 87 65

Enter the marks of student 4 in 3 subjects: 56 87 97

Enter the marks of student 5 in 3 subjects: 45 67 89

Enter the marks of student 6 in 3 subjects: 66 77 88

Enter the marks of student 7 in 3 subjects: 76 87 98

Enter the marks of student 8 in 3 subjects: 67 88 66

Enter the marks of student 9 in 3 subjects: 66 75 78

STUD NO   MARKS IN 3   TOTAL      AVERAGE

                   SUBJECTS       MARKS

 0                 78  89  90        257            85.67

1                  98  87  76        261            87.00

2                  67  78  89        234            78.00

3                  90  87  65        242            80.67

4                  56  87  97        240            80.00

5                  45  67  89        201            67.00

6                  66  77  88        231            77.00

7                  76  87  98        261            87.00

8                  67  88  66        221            73.67

9                  66  75  78        210            73.00

CLASS AVERAGE = 78.90

26. Write a program to read a two-dimensional array marks which stores marks of 5 students in 3 subjects. Write a program to display the highest marks in each subject.

#include <stdio.h>

#include <conio.h>

int main()

{

int marks [5] [3], i, j, max_marks;

for (i=0;i<5;i++)

{

printf("\n Enter the marks obtained by student %d", i);

for(j=0;j<3;j++)

{

printf("\n marks [%d] [%d] = ", i, j);

scanf("%d", &marks [i][j]);

}

}

for(j=0;j<3;j++)

{

max marks = marks [0] [j];

for (i=1;i<5; i++)

{

if (marks [i] [j] >max_marks)

max_marks = marks [i] [j];

}

printf("\n The highest marks obtained in the subject %d %d", j, max marks);

}

getch();

return 0;

}

Output

Enter the marks obtained by student 0

marks [0] [0] = 89

marks [0] [1] = 76

marks [0] [2] = 100

Enter the marks obtained by student 1

marks [1] [0] = 99

marks [1] [1] = 90

marks [1] [2] = 89

Enter the marks obtained by student 2

marks [2] [0] = 67

marks [2] [1] = 76

marks [2] [2] = 56

Enter the marks obtained by student 3

marks [3] [0] = 88

marks [3] [1] = 77

marks [3] [2] = 66

Enter the marks obtained by student 4

marks [4] [0] = 67

marks [4] [1] = 78

marks [4] [2] = 89

The highest marks obtained in the subject 0 = 99

The highest marks obtained in the subject 1= 90

The highest marks obtained in the subject 2 = 100

Programming in C: Unit II (a): Arrays : Tag: : with Example C Programs - Two-Dimensional Arrays