What is going on here?

This is a routine to read a current sensor (Sparkfun BOB-08882) I am averaging ten successive reading in order to smooth the results. The ten individual readings look OK but look at the average! I understand that the analog pins share a single ADC, and that there are timing issues when several analog pins are being read, but in this case no other analog pins are being used. To my simple mind this defies digital logic; ten digital values are added, then the sum is divided by 10, but the result is not the average.???

int ReadCurrent()
{
  int adc;
  int sum;
  int curr;
  for(int i=0; i<10; i++){
    adc = analogRead(currentPin);
    delay(2); //wait for it
    Serial1.print("adc = ");
    Serial1.println(adc);
    sum += adc;
    delay(2);
  }
  adc = sum/10;
  Serial1.print("average adc = ");
  Serial1.println(adc);
  curr = (adc - 511) * 70;
  return curr;
}

This is a typical printout:
adc = 520
adc = 520
adc = 506
adc = 509
adc = 503
adc = 521
adc = 522
adc = 518
adc = 510
adc = 507
average adc = 663

The Arduino board is a Mega(ATmega1280)

sum = 0 and it will work.

Thanks Erdin. I tried it and you are right. I’ve never seen that happen before. I will research it and try to try to see why it happened.

glenz:
Thanks Erdin. I tried it and you are right. I've never seen that happen before. I will research it and try to try to see why it happened.

Since sum lives on the stack, it is not initialized to zero by default and you didn't specify any initialization so....