0% found this document useful (0 votes)
7 views

11 TwoDim Arrays

The document discusses two-dimensional arrays in C. A two-dimensional array allows storing a table of values in rows and columns. It can be declared using syntax like type array_name[row_size][column_size]. Individual elements are accessed using two indices, such as array_name[row][column]. Two-dimensional arrays are stored in memory in a row-major order, with the first row stored sequentially starting from the base address. Functions can operate on two-dimensional arrays by passing the base address, number of rows and columns as parameters.

Uploaded by

Tapan Badhei
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

11 TwoDim Arrays

The document discusses two-dimensional arrays in C. A two-dimensional array allows storing a table of values in rows and columns. It can be declared using syntax like type array_name[row_size][column_size]. Individual elements are accessed using two indices, such as array_name[row][column]. Two-dimensional arrays are stored in memory in a row-major order, with the first row stored sequentially starting from the base address. Functions can operate on two-dimensional arrays by passing the base address, number of rows and columns as parameters.

Uploaded by

Tapan Badhei
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

Multi-Dimensional Arrays

1
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
Two Dimensional Arrays
We have seen that an array variable can store a list of values.
Many applications require us to store a table of values.

Subject 1 Subject 2 Subject 3 Subject 4 Subject 5


Student 1 75 82 90 65 76

Student 2 68 75 80 70 72

Student 3 88 74 85 76 80

Student 4 50 65 68 40 70
Two Dimensional Arrays
Subject 1 Subject 2 Subject 3 Subject 4 Subject 5
Student 1 75 82 90 65 76

Student 2 68 75 80 70 72

Student 3 88 74 85 76 80

Student 4 50 65 68 40 70

The table contains a total of 20 values, five in each line.


• The table can be regarded as a matrix consisting of four rows and five columns.

C allows us to define such tables of items by using two-dimensional arrays.


Declaring 2-D Arrays
General form:
type array_name [row_size][column_size];

Examples:
int marks[4][5];
float sales[12][25];
double matrix[100][100];

First index indicates row, second index indicates column.


Both row index and column index start from 0 (similar to what we had for 1-d arrays)
Declaring 2-D Arrays

int m[4][5];

Column 0 Column 1 Column 2 Column 3 Column 4

Row 0 m[0][0] m[0][1] m[0][2] m[0][3] m[0][4]


Row 1 m[1][0] m[1][1] m[1][2] m[1][3] m[1][4]
Row 2 m[2][0] m[2][1] m[2][2] m[2][3] m[2][4]
Row 3 m[3][0] m[3][1] m[3][2] m[3][3] m[3][4]

5
Accessing Elements of a 2-D Array
Similar to that for 1-D array, but use two indices.
• First index indicates row, second index indicates column.
• Both the indices should be expressions which evaluate to integer values.

Examples:
x[m][n] = 0;
c[i][k] += a[i][j] * b[j][k];
val = sqrt( arr[j*3][k+1] );
How is a 2-D array is stored in memory?
Starting from a given memory location (starting address of the array), the elements are stored
row-wise in consecutive memory locations.
• x: starting address of the array in memory
• c: number of columns
• k: number of bytes allocated per array element, e.g., sizeof(int)

• a[i][j] is allocated memory location at address x + (i * c + j) * k

a[0]0] a[0][1] a[0]2] a[0][3] a[1][0] a[1][1] a[1][2] a[1][3] a[2][0] a[2][1] a[2][2] a[2][3]
Row 0 Row 1 Row 2
Array Addresses Output

int main() 3221224480


3221224484
{ 3221224488
int a[3][5]; 3221224492
int i,j; 3221224496

3221224500
for (i=0; i<3;i++) 3221224504
{ 3221224508
3221224512
for (j=0; j<5; j++) 3221224516
printf("%u\n", &a[i][j]);
printf("\n"); 3221224520
3221224524
} 3221224528
return 0; 3221224532
} 3221224536
8
How to read the elements of a 2-D array?
By reading them one element at a time
for (i=0; i<nrow; i++)
for (j=0; j<ncol; j++)
scanf (“%f”, &a[i][j]);
• The ampersand (&) is necessary.
• The elements can be entered all in one line or in different lines.

We can also initialize a 2-D array at the time of declaration:


int a[MAX_ROWS][MAX_COLS] = { {1,2,3}, {4,5,6}, {7,8,9} };
How to print the elements of a 2-D array?
By printing them one element at a time.
for (i=0; i<nrow; i++)
for (j=0; j<ncol; j++)
printf (“%f ”, a[i][j]);
• This will print all elements in one line

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


printf(“\n”);
for (j=0; j<ncol; j++)
printf (“%f ”, a[i][j]);
}
• The elements are printed with one row in each line (in matrix form).
Example: Matrix addition
int main()
{ for (p=0; p<m; p++)
int a[100][100], b[100][100], for (q=0; q<n; q++)
c[100][100], p, q, m, n; c[p][q] = a[p][q] + b[p][q];

printf(“Enter dimensions: ”); for (p=0; p<m; p++)


scanf (“%d %d”, &m, &n); {
printf (“\n”);
for (p=0; p<m; p++) for (q=0; q<n; q++)
for (q=0; q<n; q++)
printf (“%d ”, c[p][q]);
scanf (“%d”, &a[p][q]);
}
for (p=0; p<m; p++) return 0;
for (q=0; q<n; q++) }
scanf (“%d”, &b[p][q]);
11
Passing 2-d arrays to functions

12
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
Passing 2-D arrays to functions

Similar to that for 1-D arrays.


• The array contents are not copied into the function.
• Rather, the address of the first element is passed.

For calculating the address of an element in a 2-D array, the function needs:
• The starting address of the array in memory (say, x) a[i][j] is located at memory
address x + (i * c + j) * k
• Number of bytes per element (say, k)
• Number of columns in the array, i.e., the size of each row (say, c)

The above three pieces of information must be known to the function.


Example

void add (int x[][25], int y[][25], int rows, int cols)
{
int main()
{ }
int a[15][25], b[15]25];


add (a, b, 15, 25);

… We can also write
}
int x[15][25], y[15][25];
But at least 2nd dimension
must be given

14
Example: Matrix addition with functions

void ReadMatrix(int A[][100], int x, int y)


{
int i, j;
for (i=0; i<x; i++)
for (j=0; j<y; j++)
scanf (“%d”, &A[i][j]);
}

void AddMatrix( int A[][100], int B[][100], int C[][100], int x, int y)
{
int i , j;
for (i=0; i<x; i++)
for (j=0; j<y; j++)
C[i][j] = A[i][j] + B[i][j];
15
}
Example: Matrix addition int main()
{
int a[100][100], b[100][100],
void PrintMatrix(int A[][100], int x, int y) c[100][100], p, q, m,
{ n;
int i, j;
printf(“\n”); scanf (“%d%d”, &m, &n);
for (i=0; i<x; i++)
{ ReadMatrix(a, m, n);
for (j=0; j<y; j++) ReadMatrix(b, m, n);
printf (“ %5d”, A[i][j]);
printf(“\n”); AddMatrix(a, b, c, m, n);
}
} PrintMatrix(c, m, n);
return 0;
}
16
Example: void add( int x[ ][25], int y[ ][25], int m, int n, int z[ ][25] )
{
int p, q;
for (p=0; p<m; p++)
#include <stdio.h> for (q=0; q<n; q++) z[p]q] = x[p][q] + y[p][q];
int main( ) { }
int a[15][25], b[15][25], c[15][25];
int m, n;
scanf (“%d %d”, &m, &n); Note that the number of columns has to be
for (p=0; p<m; p++) fixed in the function definition
for (q=0; q<n; q++) scanf (“%d”, &a[p][q]); • There is no difference between
for (p=0; p<m; p++) void add( int x[ ][25], … ) and
for (q=0; q<n; q++) scanf (“%d”, &b[p][q]); void add( int x[15][25], … )
add( a, b, m, n, c); • Specifying both dimensions is not
for (p=0; p<m; p++) { necessary, but not a mistake
for (q=0; q<n; q++) printf(“%f ”, c[p][q]);
printf(“\n”);
}
}
Example: Transpose of a matrix

#include <stdio.h> main()


{
void transpose (int x[][3], int n) int a[3][3], p, q;
{
int p, q, t; for (p=0; p<3; p++)
for (q=0; q<3; q++)
for (p=0; p<n; p++) scanf (”%d”, &a[p][q]);
for (q=0; q<n; q++)
{ transpose (a, 3);
t = x[p][q];
x[p][q] = x[q][p]; for (p=0; p<3; p++)
x[q][p] = t; {
} printf (”\n”);
} for (q=0; q<3; q++)
printf (”%d ”,
a[p][q]);
}
}

18
Example: Transpose of a matrix

#include <stdio.h> main()


{
void transpose (int x[][3], int n) int a[3][3], p, q;
{
int p, q, t; for (p=0; p<3; p++)
for (q=0; q<3; q++)
for (p=0; p<n; p++) scanf (”%d”, &a[p][q]);
for (q=0; q<n; q++)
{ transpose (a, 3);
t = x[p][q];
x[p][q] = x[q][p]; for (p=0; p<3; p++)
x[q][p] = t; {
} printf (”\n”);
} for (q=0; q<3; q++)
printf (”%d ”,
a[p][q]);
}
This function is wrong. Why? }

19
The Correct Version

10 20 30
void transpose (int x[][3], int n)
{ 40 50 60
int p, q, t;
70 80 90
for (p = 0; p<n; p++)
for (q = p; q<n; q++)
{
t = x[p][q];
x[p][q] = x[q][p];
10 40 70
x[q][p] = t; 20 50 80
}
} 30 60 90

20
Dynamically allocating 2-d arrays – a brief discussion

21
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
You may recall ….
We have discussed the issue of dynamically allocating space for 1-D arrays
• Using malloc()library function.

int* ptr;

ptr = (int*) malloc( 100 * sizeof(int) );

22
How to dynamically allocate a 2-d array?

Many variations possible:


1. Fixed number of rows, but variable number of columns
2. Variable number of rows, but fixed number of columns
3. Both number of rows and columns variable

We will discuss only the first variation:


Fixed number of rows, but variable number of columns

23
Fixed number of rows, but variable number of columns

Let us assume the number of rows is fixed to 3.


We can use an array of pointers of size 3, where the ith element of this array (a pointer)
will point to the ith row of the 2-d array.

int *r[3], i, c;
printf(”Enter nos. of columns of the 2-d array:”);
scanf(”%d”, &c); // each row will have c elements
for (i=0;i<3;i++)
r[i] = (int *) malloc(c*sizeof(int)); // allocate i-th row

24
Possible to have rows with different number of elements

r[0]

r[1]
r[2]

Statically allocated Dynamically allocated


pointer array memory

25
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *r[3], i, j, col;
for(i=0; i<3; ++i) {
col = 2 * (i+1);
r[i] = (int *) malloc (col*sizeof(int));
for(j=0; j<col; ++j)
r[i][j] = i + j;
0 1
} 1 2 3 4
for(i=0; i<3; ++i) { 2 3 4 5 6 7
col = 2 * (i+1);
for(j=0; j<col; ++j)
printf("%d ", r[i][j]);
printf("\n");
}
return 0;
}

26
We have studied only 2-d arrays.
C allows arrays of higher dimensions as well.

27
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
Practice problems
1. Write a function that takes a n x n square matrix A as parameter (n < 100) and returns
1 if A is an upper-triangular matrix, 0 otherwise.
2. Repeat 1 to check for lower-triangular matrix, diagonal matrix, identity matrix
3. Consider a n x n matrix containing only 0 or 1. Write a function that takes such a
matrix and returns 1 if the number of 1’s in each row are the same and the number of
1’s in each column are the same; it returns 0 otherwise
4. Write a function that reads in an m x n matrix A and an n x p matrix B, and returns
the product of A and B in another matrix C. Pass appropriate parameters.

For each of the above, also write a main function that reads the matrices, calls the
function, and prints the results (a message, the result matrix etc.)

28

You might also like