简体   繁体   中英

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

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
        }
    }
}
...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM