This blog is under construction

Saturday 29 June 2013

C program to find the sum of diagonal elements of a square matrix

Write a C program to find the sum of diagonal elements of a square matrix.


  #include <stdio.h>
  #include <stdlib.h>
  int main() {
        int row, column, i, j, sum = 0, **data;

        /* get the number of rows and columns from the user */
        printf("Enter the value for row and column:");
        scanf("%d%d", &row, &column);

        if (row != column) {
                printf("Cannot be a Square matrix!!\n");
                return 0;
        }

        /* dynamically allocate memory to store input data */
        data = (int **)malloc(sizeof (int) * row);
        for (i = 0; i < row; i++)
                data[i] = (int *)malloc(sizeof (int) * column);

        /* get the input from the user */
        printf("Enter your inputs:\n");
        for (i = 0; i < row; i++)
                for (j = 0; j < column; j++)
                        scanf("%d", &data[i][j]);

        /* find the sum of diagonals */
        for (i = 0; i < row; i++)
                for (j = 0; j < column; j++)
                        if (i == j)
                                sum = sum + data[i][j];

        /* print the output */
        printf("Sum of diagonals: %d\n", sum);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter the value for row and column:3  3
  Enter your inputs:
  10  20  30
  40  50  60
  70  80  90
  Sum of diagonals: 150



No comments:

Post a Comment