Unexpected loop and serial behavior

Hello,
This is my first forum post so please let me know if I am missing any formalities in the way I present my question.
I have an ultrasonic distance sensor connected to an Elegoo (knockoff) board. My goal is to use the distance sensor to control a DC motor via a PID type structure. In order to reduce noise in the data between calculating derivatives in the PID loop, I am calculating a sample average of the measurements received from the sensor. I have begun by processing the sensor input, then storing the input in an array which I will later sum and find the average of (see abbreviated code):

//initialize variables

void setup() {
//define pins
Serial.begin(9600);
}

void loop() {
  long duration;
  long distance;
  
  // put your main code here, to run repeatedly:

  for (int i = 0 ; i <= 8; i++){
    Serial.println(i);
    // send TTL signal to sensor, process input & calculate distance
    pos[i] = distance;  //store into position array
    Serial.println(pos[i]);  //display array information corresponding to loop iteration
    delay(1000); //delay 1 second
           
      if (i == 8);{
        Serial.println(F("begin Sum Loop")); //signal when i == 8 where I will then use a for loop to calculate sample average from position array

//        for (int i = 0;i <= 8;i = i + 1){
//        int sum = 0;
//        sum = pos[i] + sum;
//        Serial.println(pos[i]);
//        } // end for loop
      } //end if loop
} //end for loop

} //end void()

The problem I am having with this code is that the if statement seems to always evaluate as “true” and print “begin sum loop” to the serial monitor even when i is less than 8 (From the previous for loop). The result is my serial monitor showing something like this:

0
60
begin Sum Loop
1
59
begin Sum Loop
2
59
begin Sum Loop
3
59
begin Sum Loop
4
59
begin Sum Loop

where the iterations 0:5 are the for loop counter, values 59,60 etc are distance readings, and the “begin sum loop” statement appears after each reading (which is what really confuses me)

Any help, knowledge, or critique of my code is very appreciated

johnvorsten:

 if (i == 8);{

That if statement is useless. I imagine things will work better after deleting that semicolon.

Power_Broker:
That if statement is useless. I imagine things will work better after deleting that semicolon.

Hah.. Thanks!