Home > Mobile >  Printing the difference of sum of diagonal elements (left - right and right - left)
Printing the difference of sum of diagonal elements (left - right and right - left)

Time:10-01

Task: The difference of the sum of diagonal elements(left - right and right - left) should be printed

#include<stdio.h>
int main()
{
    int n,r,c,i,j;
    scanf("%d",&n);
    int ar[r][c],sumd1=0,sumd2=0;
    for( i=0; i<r; i  )
    {
        for(j=0; j<c ; j  )
        {
            scanf("%d",&ar[i][j]);
        }
    }
    for( i=0; i<r; i  )
    {
        for(j=0; j<c ; j  )
        {
            if(i == j)
                sumd1 = sumd1 ar[i][j];
            if(i ==  c-j-1)
                sumd2 = sumd2   ar[i][j];
        }
    }
    printf("%d",abs(sumd1 - sumd2));

}

sample input

3                   
11 2 4

4 5 6

10 8 -12

sample output

15

For sample input, my result is 0.

CodePudding user response:

#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>
int main()
{

    int n, j;
    int i=0,RightDiagonalSum=0,LeftDiagonalSum=0, firstarray, secondarray;

    scanf("%d",&n);
    int a[n][n];

    for(int firstarray = 0; firstarray < n; firstarray  )
    {
        for(int secondarray = 0; secondarray < n; secondarray  )
        {

            scanf("%d",&a[firstarray][secondarray]);
        }
    }

    while(i<n)
    {
        RightDiagonalSum=RightDiagonalSum a[i][i];
        i  ;
    }

    j=n-1,i=0;

    while(i<n)
    {
        LeftDiagonalSum=LeftDiagonalSum a[i][j];
        i  ;
        j--;
    }

    printf("%d",abs(RightDiagonalSum-LeftDiagonalSum));
    return 0;
}

  •  Tags:  
  • c
  • Related