What if you want to pick between two possibilities? If you are trying to decide between a couple of things to do, you might flip a coin and do one thing if it lands as heads and another if it is tails. In programming, you can use the if keyword followed by a statement or block of statements and then the else keyword also followed by a statement or block of statements.
// A block if/else statement
if (boolean expression)
{
statement1;
statement2;
}
else
{
do other statement;
and another one;
}
// A single if/else statement
if (boolean expression)
Do statement;
else
Do other statement;
The following flowchart demonstrates that if the condition (the boolean expression) is true, one block of statements is executed, but if the condition is false, a different block of statements inside the else clause is executed.
If/else statements can also be used with relational operators and numbers like below. If your code has an if/else statement, you need to test it with 2 test-cases to make sure that both parts of the code work.
If statements can be nested inside other if statements. Sometimes with nested ifs we find a dangling else that could potentially belong to either if statement. The rule is that the else clause will always be a part of the closest if statement in the same block of code, regardless of indentation.
Try the following code with a dangling else. Notice that the indentation does not matter to the compiler (but you should make it your habit to use good indentation just as a best practice). How could you get the else to belong to the first if statement?
if (boolean expression)
{
Do statement;
}
else
{
Do other statement;
}
A two way selection (if/else) is written when there are two sets of statements: one to be executed when the Boolean condition is true, and another set for when the Boolean condition is false.
The body of the “if” statement is executed when the Boolean condition is true, and the body of the “else” is executed when the Boolean condition is false.
Run the following code to see what it prints out when the variable age is set to the value 16. Change the variable age’s value to 15 and then run it again to see the result of the print statement in the else part. Can you change the if-statement to indicate that you can get a license at age 15 instead of 16? Use 2 test cases for the value of age to test your code to see the results of both print statements.
The following program should print out “x is even” if the remainder of x divided by 2 is 0 and “x is odd” otherwise, but the code is mixed up. Drag the blocks from the left and place them in the correct order on the right. Click on Check Me to see if you are right.
Try the following code. Add an else statement to the if statement that prints out “Good job!” if the score is greater than 9. Change the value of score to test it. Can you change the boolean test to only print out “Good job” if the score is greater than 20?