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.
Click Next for a quiz on if statements.