Tutorial - Multidimensional Arrays - Part 2


Submit solution

Points: 1 (partial)
Time limit: 4.0s
Memory limit: 64M

Author:
Problem type
Allowed languages
C

Tutorial

Compiled from multiple sources from the internet. For practice kindly use the IDE.

Multidimensional Arrays Tutorial - Part 2

Pointers and 2D Arrays

As we know that the one dimensional array name works as a pointer to the base element (first element) of the array. However in the case 2D arrays the logic is slightly different. You can consider a 2D array as collection of several one dimensional arrays.

So abc[0] would have the address of first element of the first row (if we consider the above diagram number 1).Similarly abc[1] would have the address of the first element of the second row.

Example:

#include <stdio.h>
int main()
{
   int abc[5][4] ={
            {0,1,2,3},
            {4,5,6,7},
            {8,9,10,11},
            {12,13,14,15},
            {16,17,18,19}
            };
    for (int i=0; i<=4; i++)
    {
        /* The correct way of displaying an address would be
         * printf("%p ",abc[i]); but for the demonstration
         * purpose I am displaying the address in int so that
         * you can relate the output with the diagram above that
         * shows how many bytes an int element uses and how they
         * are stored in contiguous memory locations.
         *
         */
        printf("%d ",abc[i]);
    }
    return 0;
}

Output:

1600201376 1600201392 1600201408 1600201424 1600201440

The actual address representation should be in hex for which we use %p instead of %d, as mentioned in the comments. This is just to show that the elements are stored in contiguous memory locations. You can relate the output with the diagram above to see that the difference between these addresses is actually number of bytes consumed by the elements of that row.

The addresses shown in the output belongs to the first element of each row abc[0][0], abc[1][0], abc[2][0], abc[3][0] and abc[4][0].

Try getting and printing user inputs for 2D arrays using pointers using the IDE.

Practice Exercises:

  1. To subtract two matrices.
  2. To perform Scalar matrix multiplication.
  3. To multiply two matrices.
  4. To check whether two matrices are equal or not.
  5. To find sum of main diagonal elements of a matrix.
  6. To find sum of minor diagonal elements of a matrix.
  7. To find sum of each row and column of a matrix.
  8. To interchange diagonals of a matrix.
  9. To find upper triangular matrix.
  10. To find lower triangular matrix.
  11. To find sum of upper triangular matrix.
  12. To find sum of lower triangular matrix.
  13. To find transpose of a matrix.
  14. To find determinant of a matrix.
  15. To check Identity matrix.
  16. To check Sparse matrix.
  17. To check Symmetric matrix.
  18. To add two matrices.

Comments

There are no comments at the moment.