Search code examples
arrayscmultidimensional-arraysum

I am trying to find sum of diagonal from 2d array. But getting its address instead of its value .Can anyone explain this to me?


I was trying to sum the diagonal value in 2d array but getting different Output ( Total:4194438 ) can any one help me through this.

#include <stdio.h>
    
    int main(){
    int i,j,a,sum,total;
    
    int diagonal_arr[3][3];
    
     for(i=0;i<3;i++){
        for(j=0;j<3;j++){
            scanf("%d",&a);
            diagonal_arr[i][j]=a;
    
        }
     }
    
     for(i=0;i<3;i++){
        for(j=0;j<3;j++){
    
            if(i==j){
               sum= printf("%d\n",diagonal_arr[i][j]);
                total+=sum;
            }
        }
        printf("\n");
     }
    printf("Total= %d ",total);
    
    }

OUPUT:

Total= 4194438

Solution

  • You want this:

    ...
    total = 0;    // initialize total to 0
    
    for (i = 0; i < 3; i++){
        for (j = 0; j < 3; j++){    
            if (i == j){
               printf("%d\n", diagonal_arr[i][j]);   // you can remove this line
               total += diagonal_arr[i][j];         // add diagonal value
            }
        }
    }
    ...