#include <stdio.h>
#include <stdlib.h>
int main(void) {
int arr[3][3]={{1,2,3},{4,5,6},{7,8,9}},sr,sc,i,j;
for(i=0;i<3;i++){
for(j=0;j<3;j++){
sc=sc+arr[j][i];
}
}
printf("the sum of row =%d",sc);
for(i=0;i<3;i++){
for(j=0;j<3;j++){
sr=sr+arr[i][j];
}
}
printf("n the sum of column =%d",sr);
return EXIT_SUCCESS;
}
This is my code so the Eclipse showing sum of rows is 45 and sum of columns 390948 like number but exact answer should be sum of column=45 and sum of row is 45. I tried and got answer in an online compiler.
I am expecting get answers 45 45 for both sum
Midhun thomas is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
3
In C a stack variable (auto
storage class) is uninitialized (has no meaningful value) unless you explicitly set it a value. All your variables are auto
.
In your case you set i=0
and j=0
when you start a loop, but sr
and sc
still contain no meaningful value but garbage:
It’s not necessarily all zeroes like I show here. It can be 390948 or whatever.
The compiler can warn you about this. Just turn on optimizations (e.g. -O2
) in your project: (depending on your Eclipse version) go to Project Properties -> C/C++ Build -> Settings -> Tool Settings. Click on the triangle next to your compiler to see the drop down menu -> click on Optimization. On the right hand side next to Optimization Level choose from the drop down menu your desired level.
Once you do that your compiler would say:
a.c:11:15: warning: ‘sc’ is used uninitialized [-Wuninitialized]
11 | sc=sc+arr[j][i];
| ~~^~~~~~~~~~~~~
a.c:6:45: warning: ‘sr’ is used uninitialized [-Wuninitialized]
6 | int arr[3][3]={{1,2,3},{4,5,6},{7,8,9}},sr,sc,i,j;
| ^~
Then if you initialize sc=0
and sr=0
before accumulating the values in them it will work as you expect:
sr=0;
sc=0;
for(i=0;i<3;i++){
for(j=0;j<3;j++)
...
In an online IDE it worked because like in mine example out of luck values in these variables were zeroes.
2