Lesson 11 - Conditionals
Conditionals - If Statements
If John Park is the coolest person ever, return true. If-else Ashwin is the coolest person ever… forget about it. Else… yeah John is still the coolest person ever.
If statements are essential in C++, they allow your program to be able to account for different situations and inputs. An if statement works based on its parameter, true or false. If the boolean expression in its parameter evaluates to true, then it will execute the code within the if statement and exit the conditional block. For example:
Here, the parameter in the if statement evaluates to true, so the program outputs “yes!” However, if someone (for some strange, odd reason) defined johnIsCool as false, then the program would skip the code within the if statement and continue on with the program.
Conditionals - Else… If Statements
To add more functionality to our programs, we also have the if-else and else conditional statements. If the if statement does not evaluate for true, it will check the next if-else statement(s) and if one evaluates to true it will run that one and skip checking the rest. If one does not evaluate to true, it will run the code in the else statement (assuming there is one).
Since Ashwin and John both evaluate as cool, the program realizes this and passes the first if statement and if-else statement and then runs the else block.
VERY IMPORTANT NOTE: If statements, for loops, while loops, else statements, and control statements can all be put inside of each other. That is to say, you could a for loop inside an if statement that is inside an else statement.
Conditionals - VEX Usages
In VEX, you may have already guessed that this can be particularly useful when dealing with each subsystem of the robot. Perhaps you might want to check if a button is pressed to activated a subsystem or not, perhaps you might want to check if a lift is in it top position and ensure that it doesn’t try to go even further upward and break, or maybe you want to check what autonomous mode is selected and run the correct program. We’ll see much more implementation of this later on in the course.