'C adding to values for no reason [closed]
int sum1 = aboveMain(matrice);
printf("%d nice\n", sum1);
int sum2 = underMain(matrice);
printf("%d nice\n", sum2);
For some reason this works perfectly fine, prints the intended values 11 and 19. Yet the moment i delete the printf line after the int sum1 declaration like so...
int sum1 = aboveMain(matrice);
int sum2 = underMain(matrice);
printf("%d nice\n", sum2);
It returns 30, which means its been adding them both. Yet this seems to make 0 sense to me, can anybody please explain to me why this is happening? thanks
heres the entire code btw
#include <stdio.h>
#define ROWS 3
#define COLS 3
int aboveMain(int matrice[][COLS]);
int underMain(int matrice[][COLS]);
void main() {
int matrice[3][3] = {{1,2,3},
{4,5,6},
{7,8,9}};
int sum1 = aboveMain(matrice);
printf("%d nice\n", sum1);
int sum2 = underMain(matrice);
printf("%d nice\n", sum2);
}
int aboveMain(int matrice[][COLS]) {
int sum, i, j;
for(i=0;i<3;i++) {
for(j=0;j<3;j++) {
if(i < j)
sum+= matrice[i][j];
}
}
return sum;
}
int underMain(int matrice[][COLS]) {
int sum, i, j;
for(i=0;i<3;i++) {
for(j=0;j<3;j++) {
if(i > j)
sum+= matrice[i][j];
}
}
return sum;
}
Solution 1:[1]
sum is not initialized to 0 in your functions,with the C language the initial value of local variables is undetermined. Therefore the bahaviour of your code is undefined.
int aboveMain(int matrice[][COLS]) {
int sum = 0; // you need to initialize sum to 0 here
int i, j;
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
if (i < j)
sum += matrice[i][j];
}
}
return sum;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
