C Program to Find the Sum of Diagonal Elements of Matrix

In this C program, We will show “How to find the sum of Diagonal Elements of a Matrix ” with Easy logic. We, also see, “How to print the sum of Diagonal Elements of a Matrix by taking and without taking user input”. So, let’s do it …

Finding and Printing the Sum of a Diagonal Matrix without Taking User Input

#include<stdio.h>
int main()
{
    int A[3][3] = {{1,2,3},{4,5,6},{7,8,9}}, i, j, sum=0;

   //Printing the A matrix.
   printf("A Matrix is: \n");
   for(i=0; i<3; i++)
    {
        for(j=0; j<3; j++)
        {
            printf("%d ",A[i][j]);
        }
        printf("\n");
    }

   // Applying Condition to Sum the Diagonal of A matrix.
   for(i=0; i<3; i++)
    {
        for(j=0; j<3; j++)
        {
           if(i==j)
             sum = sum + A[i][j];
        }
        printf("\n");
    }

    printf("The sum of Diagonal Elements is %d \n\n", sum);

    return 0;
}

Finding and Printing the Sum of Diagonal Sum of a Matrix Taking User Input

#include<stdio.h>
int main()
{
    int A[10][10], i, j, rows,colm, sum=0;

    printf("Enter the rows and column of the A Matrix: ");
    scanf("%d %d", &rows, &colm);

    while(rows!=colm)
    {
       printf("\nSorry! Enter the same amount of rows and column. \n");
       printf("Enter the rows and column of the A Matrix: ");
       scanf("%d %d", &rows, &colm);
    }

    //Getting user Input of A Matrix.
    for(i=0; i<rows; i++)
    {
        for(j=0; j<colm; j++)
        {
            printf("Enter A[%d][%d] : ",i,j);
            scanf("%d", &A[i][j]);
        }
        printf("\n");
    }

   //Printing the A matrix.
   printf("A Matrix is: \n");
   for(i=0; i<rows; i++)
    {
        for(j=0; j<colm; j++)
        {
            printf("%d ",A[i][j]);
        }
        printf("\n");
    }

   // Applying Condition to Sum the Diagonal of A matrix.
   for(i=0; i<rows; i++)
    {
        for(j=0; j<colm; j++)
        {
           if(i==j)
             sum = sum + A[i][j];
        }
        printf("\n");
    }

    printf("The sum of Diagonal Elements is %d \n\n", sum);

    return 0;
}

Keep Learning with PrologiCode.

Happy Coding.

Leave a Comment