Write your question here.
Hi. I wrote a program to find the sum of the of the gaps between adjacent entries of an array. The gap has to be absolute value between two numbers. Here is my program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
int sumGaps(int a[], int cap) {
int gap, sum;
for (int i = 1; i < cap; i++) {
int gap = a[i] - a[i - 1];
if (gap < 0) gap = -gap; sum = sum + gap;
}
return sum;
}
int main() {
int x[5] = {3, 1, 4, 1, 5};
cout << sumGaps(x, 5) << endl; // prints 12 corresponding to the sum of
gaps 2 + 3 + 3 + 4.
return 0;
}
As you can see in the main function, the correct answer is 12. However, when I ran the program, it gave me the answer of 4196783. I figured out that if I changed to declare the variable "gap" inside the for loop, it would give the correct answer. Why is this? Can anybody explain for me why declaring a variable inside vs declaring it outside the for loop make the answer change?
Thank you.
int sum; // uninitialized
// value of sum is undefined
sum = sum + 2; // undefined + 2
// value of sum is still undefined
Whether you read value 4196771 or 0 from undefined variable makes no difference.
In fact, consider yourself lucky that you got the 4196783 as hint of a problem and extremely unlucky when unrelated code change happened to produce the expected 12 by accident.
Since you're starting at index 1 and have no need to store temporary variables, can refactor to not have "gap":
1 2 3 4 5 6 7 8 9
// Expects array to have at least 2 elements
int SumGaps(int a[], int a_size)
{
int sum = 0;
for (int i=1; i<a_size; i++)
sum += abs(a[i] - a[i-1]);
return sum;
}
Thank you all for your responses.
*keskiverto* you are right. The program printed 4196771 as the result and I couldn't explain why. Now I understand. Thank again