C program to find sum of diagonal elements in a matrix

Row-major order and Column-major order: In computing, row-major order and column-major order describe methods for arranging multidimensional arrays in linear storage such as memory. The difference is simply that in row-major order, consecutive elements of the rows of the array are contiguous in memory; in column-major order, consecutive elements of the columns are contiguous.(Wiki)

C Supports Row-major order: That means if we represents a two dimensional matrix in C, At first It will traverse the first row then second row and so on.

Square Matrix: We know that square matrix is a matrix whose ROW and COLUMN are equal. If a square matrix of size n then ROW = COLUMN = n. Now see a square matrix. On which we will manipulate the main diagonal elements, elements above main diagonal, elements bellow the main diagonal.

two dimensional matrix in c

From the above image we can see that the indexes of all the diagonal elements follow a general rule, that is ROW = COLUMN, here [00], [11], [22] and [33].

Above the main diagonal we have [01], [02], [03], [12], [13] and [23]. Now notice carefully that, all these indexes follows ROW < COLUMN.

Now we have those elements which are bellow the main diagonal these are, [10], [20], [21], [30], [31], and [32]. in these case ROW > COLUMN. Now lets start with code……

#include <stdio.h>

int main(){
    int mat[10][10], array_size, row=0, col=0, diagonalSum=0, aboveSum=0, bellowSum=0;

    printf("Enter the array size\n");
    scanf("%d",&array_size);
    printf("Enter the elements of matrix\n");

    for(row=0;row<array_size;row++){
        for(col = 0;col<array_size;col++){
            printf("Enter the element at [%d%d] : ",row,col);
            scanf("%d",&mat[row][col]);
        }
        printf("\n");

    }
    // Sum of diagonal element ROW = COLUMN
    printf("The diagonal elements are \t");
    for(row=0;row<array_size;row++){
        for(col = 0;col<array_size;col++){
            if(row==col){
                printf(" %d, ",mat[row][col]);
                diagonalSum += mat[row][col];
            }
        }
    }

    printf("\nAnd the sum is %d\n\n",diagonalSum);

    // Sum of elements above diagonal  ROW < COLUMN
    printf("The elements above diagonal are \t");
    for(row=0;row<array_size;row++){
        for(col = 0;col<array_size;col++){
            if(row<col){
                printf(" %d, ",mat[row][col]);
                aboveSum += mat[row][col];
            }
        }
    }

    printf("\nAnd the sum is %d\n\n",aboveSum);

    // Sum of elements bellow diagonal  ROW > COLUMN
    printf("The elements bellow diagonal \t");
    for(row=0;row<array_size;row++){
        for(col = 0;col<array_size;col++){
            if(row>col){
                printf(" %d, ",mat[row][col]);
                bellowSum += mat[row][col];
            }
        }
    }

    printf("\nAnd the sum is %d\n\n",bellowSum);

    return 0;
}



Matrix multiplication in C with explanation

We should have basic knowledge on the representation of two dimensional matrix in C. Here is three two dimensional matrix a, b and c. a for matrix A, b for matrix B, and c for matrix C. which holds the multiplication result. i, j, k are control variable and sum is needed to hold the summation of the consecutive two products.

#include <stdio.h>
int main()
{

   int a[2][2] = {3,4,2,7};
   int b[2][2] = {6,8,5,9};
   int c[2][2], i, j, k, sum;

   printf("Matrix A is : \n\t\t");
   for(i=0;i<2;i++){
    for(j=0;j<2;j++){
        printf("%d \t",a[i][j]);    }
    printf("\n\t\t");
   }

   printf("\nMatrix B is : \n\t\t");
   for(i=0;i<2;i++){
    for(j=0;j<2;j++){
        printf("%d \t",b[i][j]);
        }
    printf("\n\t\t");
   }

   printf("\nMultiplication of matrix A and B\n\t\t");
   for(i=0;i<2;i++){
    for(j=0;j<2;j++){
        sum = 0;
        for(k=0;k<2;k++){
            sum = sum + a[i][k] * b[k][j];
             }
        c[i][j]=sum;
    }
   }
     printf("\nMatrix A*B is : \n\t\t");
    for(i=0;i<2;i++){
    for(j=0;j<2;j++){
        printf("%d \t",c[i][j]);
      }
    printf("\n\t\t");
   }

return 0;
}

Traversing a matrix

Let us consider the traversing of matrix A, we use here two for loop. One is nested in another, now consider for the first time printf("%d \t",a[i][j]); at the first time i and j enter the loop with value i=0 and j=0; so it represent the first element of matrix A with a[0][0]=3, After the first iteration j increase it's value by j =1 and the inner loop is also true in this case so it point a[0][1] = 4; At the next iteration j= 2 so the for loop is false as 2 is not greater than 2. so it execute the next line printf("\n\t\t"); which prints a new line and two tab after printing a[0][0]=3 and a[0][1] =4,

Now lets talk about the outer loop, for(i=0;i<2;i++) by this time i = 1 and then it enter the inner loop for(j=0;j<2;j++) again it runs two times and results a[1][0]=2 and a[1][1]=7.

Graphical Representation of matrix multiplication

Matrix Multiplication

It uses three for loops, the control variables are i, j, k, at the first iteration all these control variables including sum are zero so,
sum = sum + a[i][k] * b[k][j]
=> 0+a[i][k] * b[k][j]
=> 0+ a[0][0]=3 * b[0][0]= 6
=> 3*6=18
so sum =18, At the next iteration k=1, and still i=0 also j=0 therefore

sum = sum + a[i][k] * b[k][j]
=> 18+a[0][1]*b[1][0]
=>18+4*5
=>18+20
=38

At the next iteration k gets 2 so it becomes false and go to the upper loop (control variable j) and brings j=1, and still i=0, and sum initialize with 0;

sum = sum + a[i][k] * b[k][j]
=> 0 + a[i][k] * b[k][j]
=> 0 + a[0][0]=3 * b[0][1]= 8
=> 3*8=24,

At the next iteration k=1, therefore

sum = sum + a[i][k] * b[k][j]
=> 24+a[0][1]*b[1][1]
=> 24+4*9
=> 24+36=60.

And thus 47, 97 comes correspondingly.

Exception

From the above program we can see that the column of matrix A and the row of matrix B are equal 2=2,This rule must be maintain in matrix multiplication

Column number of first matrix must be equal to the row number of the second matrix

Now lets try with another programm

#include <stdio.h>
int main()
{

   int a[12][12], b[12][12] ,c[12][12], rowa, cola, rowb,colb, i, j, k, sum;

   printf("Row of the first matrix\n");
   scanf("%d",&rowa);
   printf("Column of the first matrix(a) \n");
   scanf("%d",&cola);

    printf("Enter the elements of first matrix\n");
    for (  i = 0 ; i < rowa ; i++ ){
        for ( j = 0 ; j < cola ; j++ ){
      scanf("%d", &a[i][j]);
        }
    }

   printf("Row of the second matrix\n");
   scanf("%d",&rowb);
   printf("Column of the second matrix(b) \n");
   scanf("%d",&colb);

   if(cola != rowb){
        printf("The row number of the second matrix(b) should be %d\n",cola);
        printf("Column of first matrix must be equal to the number of row of the second matrix.\n");
        printf("Run the program again.\n");
   }

   else{
        printf("Enter the elements of second matrix\n");
        for (  i = 0 ; i < rowb ; i++ ){
            for ( j = 0 ; j < colb ; j++ ){
            scanf("%d", &b[i][j]);
            }
        }

      printf("\nMultiplication of matrix A and B\n\t\t");
        for(i=0;i<rowa;i++){    // rowa ...?  [1]
            for(j=0;j<colb;j++){  // colb...?  [2] 
            sum = 0;
                for(k=0;k<rowb;k++){// rowb...?  [3] 
                    sum = sum + a[i][k] * b[k][j];
                }
            c[i][j]=sum;
        }
    }
    printf("\nMatrix A*B is : \n\t\t");
    for(i=0;i<rowa;i++){
    for(j=0;j<colb;j++){
        printf("%d \t",c[i][j]);
      }
    printf("\n\t\t");
   }
   }
return 0;
}

  1. The number of row of the product matrix is equal to the row of the first(a) matrix
  2. The number of column of the product matrix is equal to the second(b) matrix
  3. The iteration number is equal to row of the second matrix (rowb) or the column of the first matrix (cola), since both are equal.

How to convert a while loop to a for loop in c

The basic structure of for loop is as following

for(initialization; condition; adjustment){
        statement(s);
      }

So the fo loop has four parts,

  1. Initialization: We need to assign a value for the control variable.
  2. condition: We have to use a conditional expression here. The compiler execute/iterate the for loop until it get 0 or false
  3. adjustment: Adjust the control variable (by increment or decrement ) so that the condition get 0 or false
  4. statement(s): Any type of simple or compound statement(s)

The basic structure of while loop is as following

while(condition){
        statement(s);
      }

We can see that the while loop has only two parts

  1. Condition
  2. statement(s)

So if we wish to use the while loop as the for loop we need to construct it as the following

initialization;
while( condition){
        statement(s);
      adjustment;
       }

Now lets see a program using both for loop and while loop. See the factorial finding program using both for loop and while loop

#include<stdio.h>
int main(void){

int count;

printf("Using for loop\n\n");
for(count = 1;count<=5; count++){
        printf(" \t count is %d\n",count);
        }


printf("\n Using for loop\n\n");
count = 1;
while(count<=5 ){
        printf("\t count is %d\n",count);
        count++;
        }

return 0;
}