Z. Kelvin
Z. Kelvin

Reputation: 3

Why is this variable that I initialize to zero at 4 million instead?

C newbie here. Part of a lab assignment is to debug the following code. Instead of the expected output of 30 (the sum of the squares of 0, 1, 2, 3, and 4), it produces a result somewhere between 32,794 and 32,797. Through using the debugger, in the sumValues function, the variable ii is greater than 4 million on the first iteration, and I'm really not sure why. I'm betting it's something about C's initialization processes:

#include <stdio.h>

int sumValues(int v[], int length);

int main(void)
{
   int val[5], n;
   for (n = 0; n < 5; n++)
      val[n] = n * n;

   printf("the sum of entered values is %d", sumValues(val, 5)
   return 0; 
}

int sumValues(int a[], int size)
{
   int sum, ii;
   sum = 0;
   ii  = 0;

   for (ii = 0; ii <= size; ii++)
      sum += a[ii];

   return sum; 
}

(As usual, insights into the obvious thing I can't seem to find are greatly appreciated. Thanks!)

Upvotes: 0

Views: 88

Answers (2)

Tom Karzes
Tom Karzes

Reputation: 24100

In sumValues, change:

for (ii = 0; ii <= size; ii++)

to:

for (ii = 0; ii < size; ii++)

It's looking at one-too-many array entries, so it's picking up a garbage value.

Upvotes: 2

Off-by-one error:

   for (ii = 0; ii <= size; ii++)

You want this instead:

   for (ii = 0; ii < size; ii++)

The "extra" element you were reading from out of bounds happened to be a really big number.

Upvotes: 1

Related Questions