Two-way Selection: if-else Statements

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.

 1// A block if/else statement
 2if (boolean expression)
 3{
 4   statement1;
 5   statement2;
 6}
 7else
 8{
 9   do other statement;
10   and another one;
11}
1// A single if/else statement
2if (boolean expression)
3    Do statement;
4else
5    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.

../_images/Condition-two.png

Figure 1: The order that statements execute in a conditional with 2 options: if and else

Note

The else will only execute if the condition is false.

Assume you are flipping a coin to decide whether to go to a game or watch a movie. If the coin is heads then you will go to a game, if tails then watch a movie. The flowchart in Figure 2 shows the conditional control flow with 2 branches based on a boolean variable isHeads.

Module2-Choice-and-Iteration/Figures/flow_4.png:width:400px:align:center:figclass:align-center

exercise Check your understanding

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.

coding exercise Coding Exercise

Run the DriversTest program to see what it prints when the variable age is set to the value 18. Change the input value to 18 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 16 instead of 18? Use 2 test cases for the value of age to test your code to see the results of both print statements.

Recall the TestMidterm program from the previous lesson that outputs a message based on whether you passed the midterm. The program uses two separate if statements to decide what to print. Notice the second condition is simply the negation of the first condition. Rewrite this code to use a single if-else rather than two separate if 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 <i>Check Me</i> to see if you are right.

coding exercise Coding Exercise

Try the ScoreTest program. 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?

Nested Ifs and Dangling Else

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.

1// Nested if with dangling else
2if (boolean expression)
3   if (boolean expression)
4       statement1;
5   else  // belongs to closest if
6       statement2;

coding exercise Coding Exercise

Try the DanglingElseTest program. Notice that the indentation does not matter. How could you get the else to belong to the first if statement?

You can use curly brackets { } to enclose a nested if and have the else clause belong to the the top level if clause like below:

1// Nested if with dangling else
2if (boolean expression)
3{
4   if (boolean expression)
5       statement1;
6}
7else  // belongs to first if
8   statement2;

Summary

  • If statements can be followed by an associated else part to form a 2-way branch:

1if (boolean expression) {
2    Do statement;
3}
4else {
5    Do other statement;
6}
  • 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.

  • Use 2 test-cases to find errors or validate results to try both branches of an if/else statement.

  • The else statement attaches to the closest if statement.

You have attempted of activities on this page