¤ Home » Programming » C Tutorial » Arrays in C Part 2 of 2 - Multidimensional arrays

Arrays in C Part 2 of 2 - Multidimensional arrays

We have seen in the earlier article that a one-dimensional array of size n is represented as a contiguous block of n number of elements. Likewise, a two dimensional array of size m x n (here m and n are representing the two dimensions) can be represented as m numbers of one-dimensional arrays each consisting of n number of elements.

The syntax for declaring a multidimensional array is as follows:

```storage-class datatype array_name [expression1] [expression2] ... [expression n];
```

Each element in the array is accessed by the combination of array name and a pair of subscripts indicating relative position of the element in the memory. The number of subscripts depend on the dimensions of the array.

Example 2-dimensional array declaration:

```int x[3][3];
```

Example 2-dimensional array declaration along with initialization:

```int data_values[3][4]={
{1,2,3,4},
{5,6,7,8},
{10,11,12,13}
};
```

The following example of matrix manipulation illustrates the usage of multidimensional array.

```#include <stdio.h>
#define row_size 100
#define col_size 100
typedef int matrix[row_size][col_size];

main()
{
matrix a,b,c;
int i,j,k,n;
printf("Enter the matrix dimension: ");
scanf("%d ",&n); fflush(stdin);

/* accept values of elements of the two arrays a & b to form nxn matrices */
for(i=0; i < n; i++)
for(j = 0 ; j < n ; j++)
{
printf("Give matrix element with row %d column %d : ", i+1, j+1);
scanf("%d %d", &a[i][j], &b[i][j]); fflush(stdin);
c[i][j] = 0; //initialize elements of the 3rd array c to 0
}

/* matrix multiplication and creation of the resultant matrix */
for(i = 0; i < n; i++)
for(j = 0; j < n; j++)
for(k = 0; k < n; k++)
c[i][j] += (a[i][k] * b[k][j]);

/* display the resultant matrix */
printf("\n\n");
for(i=0; i < n ; i++)
{
for(j = 0; j < n ; j++)
{
printf("%d\t",c[i][j]);
}
printf("\n");
}
}
```

Exercise

Identify the array defined in each of the following statements. Indicate what values are assigned to the individual array elements.

```int a[2][4] = {
{5,4,3,2},
{9,8,7,6}
};

int data[2][3][4] = {
{
{3,2,1},
{9,8},
{5,4,6,7}
},
{
{1,2},
{},
{2,3,4}
}
};

char room_colours[3][7] = {
{'B', 'l', 'u', 'e','\0'},
{'G', 'r', 'e', 'e', 'n','\0'},
{'Y', 'e', 'l', 'l', 'o', 'w','\0'}
};
```

Passing multidimensional array as parameter to a function

The formal argument declaration within a function definition must include explicit size specifications of all the subscripts except the first. The size specification must be consistent with the corresponding size specification in the calling program. The first subscript position should be written with an empty pair of square brackets as in one-dimensional array. See example below for more clarity.

```#include <stdio.h>
#define  row_size 50
#define  col_size 50

main()
{
int a[row_size][col_size], b[row_size][col_size], c[row_size][col_size];
int m,n,k;
void read_data(int x[][col_size], int nrows, int ncols);
void matrix_mult(int x[][col_size], int y[][col_size], int z[][col_size], int nrows, int ncols1, int ncols2);

...
matrix_mult(a, b, c, m, n, k);
...
}

void matrix_mult(int x[][col_size], int y[][col_size], int z[][col_size], int nrows,int ncols1, int ncols2)
{
int i,j,k;
for(i=0; i < nrows; ++i)
for(k=0; k < ncols2; ++k)
{
z[i][k] = 0;
for(j=0; j < ncols1; ++j)
z[i][k] += x[i][j] * y[j][k];
}
return;
}
```

Two dimensional character array

A two-dimensional character array consists of a collection of single dimensional character array. Each 1-dimensional character array is a string. The declaration of a two-dimensional character array does not differ much from two-dimension array declaration of integer data, except that each individual string is terminated by a null character.

The syntax for declaring a two dimensional character array is as follows:

```char name [3][20];
```

The variable name is a two dimensional string capable of storing 3 strings, where maximum length of each string is 19 characters (one position is kept aside for null). The initialization of such an array of strings can be performed in either of the two ways as shown below:

```char city[4][10]={
{"Calcutta"},
{"Bombay"},
{"Delhi"}
};
```

The above way of initializing automatically adds a null character (\0) to the end of each string.

```char city[4][10]={
{'C', 'a', 'l', 'c', 'u', 't', 't', 'a', '\0'},
{'B', 'o', 'm', 'b', 'a', 'y', '\0'},
{'M', 'a', 'd', 'r', 'a', 's', '\0'},
{'D', 'e', 'l', 'h', 'i', '\0'}
};
```

The above character array will be represented in the memory as shown below:

For beter understanding of how to use a 2-dimensional array of strings in a C program, observe the following sample program. Also try it out on your computer.

```#include <stdio.h>
#define  r  10
#define  c  30
main()
{
char name[r][c], chr;
int i,j;
for(i=0; i < r; i++)
{
printf("Enter Name #%d: ", i+1);
j = 0;
while(((chr=getchar()) != ‘\n') && j< (c – 1))
{
name[i][j] = chr;
++j;
}
name[j] = '\0';
}
for(i=0; i < r; i++)
printf("Name %d is : %s\n", i+1, name[i]);
}
```

Exercise

Match the following :

 i. arr_ele[3] a. index ii. subscript b. three dimensional array iii. int num[3][4] c. fourth element of an array iv. int num[4][3] d. two dimensional array with 3 rows and 4 columns v. int num[3][4][5] e. two dimensional array with 4 rows and 3 columns

Lab Work

1. Write an interactive C program to process the marks obtained in a test for a group of students in the programming language course. The total number of tests to be conducted for the students is specified by the user at the beginning of the program. For each student in the class the program expects student's name and marks obtained in each test. It then calculates the average score for each student, and an overall class average (an average of the individuals student averages). The information to be displayed includes subject name, number of tests conducted and the overall class average, followed by the performance of each student that in turn includes the name of the student; the individual test scores and the average score for each student.

Hint: The student names should be stored in two-dimensional character array. A separate two dimensional floating point array should be used for storing the examination scores. The performances of the students are to be displayed as shown below:

 Test scores (percent) Name Test 1 Test 2 Test 3 Test 4 Test 5 Average ---------------------------------------------------------------------------------------------------- Mehul 45 80 80 95 55 75 Ravi 60 50 70 75 55 80 Raj 40 30 10 45 60 55 Pravin 0 5 5 0 10 5 ---------------------------------------------------------------------------------------------------- Class Average 53.75

2. Consider the following list of States and their Capitals:

 West Bengal Kolkata Jharkhand Ranchi Orissa Bhubaneswar Maharashtra Mumbai Kerala Thiruvanantapuram Gujarat Gandhinager Haryana Chandigarh Uttar Paradesh Lucknow Madhya Paradesh Bhopal Himachal Paradesh Shimla

Write an interactive C program that will accept the name of a state as input and print the corresponding capital, and vice-versa. Entering the word End as input will terminate the program.

3. There are 500 light bulbs (numbered 1 to 500) arranged in a row. Initially, they are all OFF (indicating by 0). Starting with bulb 2, all even numbered bulbs are turned ON. Next starting with bulb 3, and visiting every third bulb, it is turned ON if it is OFF, and it is turned OFF if it is ON. This procedure is repeated for every fourth bulb, every fifth bulb, and so on up to the 500th bulb. Write a program to determine which bulbs are OFF at the end of above procedure.

4. Write a C function called merge() to merge two sorted arrays so that the merged data is also sorted. Use merge function recursively to sort an array of unsorted data.

Share:

Web Service Offers

Looking to build a website?
Launch a 5 page website in 1 day at only Rs.499/year. Hosting included.