An “If” statement, also known as a conditional, is a control flow structure that allows a program to execute different blocks of code based on whether a specified condition is true or false.
In programming, an “if” statement is used to determine whether a section of code should run or not run. Generally, an “if” statement starts with the word “if”, is followed by a boolean expression, followed by the code that should be run if the condition is true. “If” statements can optionally include an “else” statement that will be run if the condition is false. It is good practice to always use an “else” statement to make sure that all conditions are accounted for.
A boolean expression is just a logical statement where the entire statement is either true or false. Some examples of boolean expressions are:
x>3
- If x is greater than 3, the condition is true, otherwise it’s not.
It’s Tuesday and it’s sunny outside.
- Both things need to be true for the statement to be true
A cat is black or orange and has a big fluffy tail.
- The cat can either be black or orange, but it has to have a big fluffy tail
In Java, an “if” statement looks like this:
If (j>3) {
j = 1;
}
In FTC, some of the things we use “if” statements for is:
To see if a button is pressed on the gamepad
To check if the value returned by a color sensor is in a certain range
To see how much time is left in autonomous
To check if an encoder value is greater than a known value
“If” statements allow us to
Run a section of code repeatedly
Run certain code if certain conditions are met
Always run a section of code
Cause errors and break things
Which of the following is true of a boolean expression
Their meaning is unclear
They can only check for one thing
They aren’t used in “if” statements
The entire expression is either true or false
When might we want to make use of an “else” statement
We want to have the program run some code if the condition is false
We aren’t able to use “else” statements
We always have to use an “else” statement
We want to run the if statement multiple times
Which of the following would NOT be a use of an “if” statement
Check if a button is pressed on the gamepad
Define the highest position of a lift.
Check the value returned from our camera to see what range it’s in
Check a gyroscope value to see if we’re pointed in the right direction