Instructional Material: IF Statement

Once we are able to compare values (variables) and arrive at a boolean true/false (or yes/no) value, we need a way to act on that boolean value. With comparisons we are essentially asking a question and will change program flow based on the answer. We ask questions with flow control statements, the first of which is if. The general form of the if statement is:

Here we are asking if the boolean-value (comparison result) is true and if so execute the statement. If the answer is false, don't execute the statement. The boolean-value that is the result of a comparison expression also called a condition. Note that only one statement my follow the if, but you may use a statement block { } (curly braces) to control multiple statements. With curly braces all of the statements between the two braces are executed. Here are some examples (assume x = y = 0):

So far we are just choosing to execute the statement conditioned by the if or not. What if we want to choose between two actions, one if the boolean-value is true and another if it is false. That is where else comes in. Here is the form of the if else statement:

Here, if the boolean-value is true, statement-1 is executed and if boolean-value is false, statement-2 is executed. One of the statements will be executed. Assuming x = y = 0, here are some examples:

The final form if the if statement is if else if. This form allows us to ask another question on the else branch to further decide which statement to execute. The form of the if else if is:

Assuming x = y = 0, here are some examples:

Watch this video for more about flow control with if (stop at the switch statement, we will cover it later). Here is a detailed discussion of if.

Whenever there are multiple options on an if statement you are trying to write (if I see blue I will do this, if I see red I will do that, if I see green I will do a third thing, if I see nothing I will stop), note that while we can use multiple if statements in a row, we should to use else if statements to link them together. Using multiple simple if statements can result in incorrect behavior. Do not just stack if statements together.
 
In robotics, the if statement is used to check the status of controller buttons, sensors or other input devices and decide what the robot should do in response.
 
Here is the example code in CodingGround.

Click Next for a quiz on if statements.

 

Material Type: 
Lecture/Presentation
Education Level: 
Middle School
High School
Focus Subject: 
Computing / Computer Science
Robotics Software
HW Platform: 
EV3
SW Platform: 
Java
Interactivity Style: 
Mixed
Audience: 
Learner