How to Program with a While Loop in VEX C++

Get more with VEXcode
We recommend you transition to our new software. VEXcode has both block-based and text-based options, that work on Chromebooks, iPads, Android tablets, Windows and Macs. Visit code.vex.com for more details on how to download VEXcode.
VEX Coding studio has been discontinued and is no longer available for download. Already downloaded? The program will continue to function but will no longer be supported.
Users who transition to VEXcode can migrate their C++/C++ Pro projects to VEXcode Text by following this article.

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

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

NOTE: Those shown in the example above display a message and spin the robot clockwise. In the example, the loop makes the displayed message display repeatedly until it runs off of the screen. 

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

Code that can be copied and pasted:

#include "robot-config.h"

int main() {
    //Loop to have the robot spin clockwise and display "It is true and the loop continues!"
    while(true){
        Brain.Screen.print("It is true and the loop continues!");
        LeftMotor.spin(directionType::fwd);
        RightMotor.spin(directionType::rev);
    }
}

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

  • Inside  of  int 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 commands. 

NOTE: In the example above, the two commands inside the while loop's curly braces keep both motors stopped when 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 commands 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 "robot-config.h"
          
int main() {
    //Loop to have the robot remain stationary until the screen is pressed.
    while(Brain.Screen.pressing() == false) {
      LeftMotor.stop();
      RightMotor.stop();
    }

    Brain.Screen.print("I've been pressed and I'm moving forward for 3 seconds!");
    LeftMotor.spin(directionType::fwd);
    RightMotor.spin(directionType::fwd);
    task::sleep(3000);
    LeftMotor.stop();
    RightMotor.stop();
}