While loop question

I am having my students using while loops. We are using time as the condition which governs whether the program continues or not. Yet, in this program, the program continues to run until the left and right motors have reached the number of turns indicated. All of this takes much longer than five seconds. I was taught that a while loop governs everything inside of the brackets. Why is this happening? Thanks!

The condition for the while loop will only be evaluated once for each iteration of the loop. As spinFor is a blocking command (when used without the optional waitForCompletion parameter), both moves for the Right motor will need to complete before the condition is evaluated for a subsequent iteration.

I see what you are trying to do, but it won’t work that way.

7 Likes

To add onto James’s answer, the program is behaving correctly, your interpretation of what the program intends is incorrect. For example:

int main()
{
    while(Brain.Timer.time(seconds) < 5) {
       waitFor(15, seconds);
    }
    printf("Brain.Timer.time is now %d", (int)Brain.Timer.time(seconds));
}

Will print 15 and not 5 because the waitFor statement takes 15 seconds to return, at which point the while loop evaluates Brain.Timer.time(seconds) < 5 for the second time, sees it is false, and exits the loop.

Similarly:

int main()
{
    while(Brain.Timer.time(seconds) < 5) {
       waitFor(2, seconds);
    }
    printf("Brain.Timer.time is now %d", (int)Brain.Timer.time(seconds));
}

Will print out 6 seconds, as it makes it thru the loop 3 times before the while condition is false.

3 Likes

Consider also this program:

int main() {
  int i = 0;
  while(i >= 0) {
      i = -1;
      i = 10;
  }
  printf("Exited while loop %d\n",i);
}

What will this program do? What will it print out?

3 Likes