While Loop - Tutorials

Use a while(true) loop to have the program repeat commands forever.

  • Inside of main, add a while(true) control structure.
  • Within the curly braces, add instructions.

NOTE: Those shown in the example above display a message and spin the robot clockwise.

NOTE: Use // notation to include comments that explain what that section of code does.

Code that can be copied and pasted:
#include "vex.h"
 
using namespace vex;
 
int main() {
 // Initializing Robot Configuration. DO NOT REMOVE!
 vexcodeInit();
 while (true) {
   Brain.Screen.setCursor(1, 1);
   Brain.Screen.print("It is true and the loop continues");
   Brain.Screen.clearScreen();
   LeftMotor.spin(forward);
   RightMotor.spin(reverse);
   wait(200, msec);
 }
}

Or, use while() loop to have the program repeat the same instructions while a condition is true.

  • Inside of main add a while() control structure.
  • Inside of the while() parentheses, add a condition for the program to check
NOTE: In the example above, the condition being checked is whether the Brain's screen is pressed. In this case, the while loop will continue while the screen is not pressed because the condition is set to false.
Within the curly braces of the while(Brain.Screen.pressing()==false) structure, add instructions.
NOTE: In the example above, the two commands inside the while loop's curly braces keep both motors stopped while the screen is not pressed. The program stays within that loop unless the Brain's screen is pressed. If/when it is, the program breaks out of the loop and continues with the next instructions in the program: displaying a message and moving forward for three seconds before stopping.
NOTE: Use // notation to include comments that explain what the section of code does.
Code that can be copied and pasted:
#include "vex.h"
 
using namespace vex;
 
int main() {
 // Initializing Robot Configuration. DO NOT REMOVE!
 vexcodeInit();
 // Loop to have the robot remain stationary until the screen is pressed.
 while (Brain.Screen.pressing() == false) {
   LeftMotor.stop();
   RightMotor.stop();
   wait(5, msec);
 }
 
 Brain.Screen.print("I'm moving forward for 3 seconds!");
 LeftMotor.spin(forward);
 RightMotor.spin(reverse);
 wait(3, seconds);
 LeftMotor.stop();
 RightMotor.stop();
}