ICS3U: Introduction to Computer Science, Grade 11, University Preparation

Unit 2: Introduction to Programming

Activity 4: Selection Control Structure

Learning Goal: By the end of this activity, I will be able to create simple programs using the selection (if, switch) control structure.

Content


You make decisions every day. Will you have toast for breakfast today or will you have eggs? Will you take an umbrella with you today because it is raining or will you leave your umbrella at home? Decisions allow you to take a certain action based on some condition. For example, the condition could be, "is it Saturday morning?" If it is Saturday morning, then you will sleep in, but if it is not Saturday morning then you will get up early.

Computers can also be programmed to make decisions. These decisions allow the program to take certain actions based on certain conditions. This makes the program more functional and more flexible.

Selection Control Structure

In the first three activities, you have become familiar with the sequential control structure, where one statement after another in a computer program is executed in order. In this activity, you will use several selection control structures that allow the computer program to execute the statements in a different order.

You can use a selection control structure when you want the computer to choose between alternative actions. You make a conditional statement that is either true or false. If the conditional statement is true, the computer executes another statement or set of statements. If it is false, it executes a different statement or set of statements. The computer's ability to solve practical problems is an outcome of its ability to make decisions and execute different statements.

Boolean Expressions

In programming languages, a condition takes the form of a Boolean expression (sometimes called a logical expression). Every Boolean expression has one of the two Boolean values: true or false.

Boolean expressions can be created in the following ways:

Comparison Operators

Comparison (or relational) operators test a relationship between two values and determine if the relationship is true or false.

Operator Relationship Tested
== Equal to
!= Not equal to
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to

If Statement

The if statement is the fundamental selection control structure that allows the computer program to select certain statement(s) to execute. With it, you can test a relationship and choose a course of action.

The if statement comes in two forms, the if form and the if-else form.

If form
If-Else form
Sometimes you run into a situation where you want to say, “If a certain condition is true, perform some action; otherwise, don't do anything.” The If form of the If statement would be used in this case. Sometimes you run into a situation where you want to say, “If a certain condition is true, perform one action; else perform a different action.” The computer performs just one of the two actions under any given set of circumstances. The If-Else form of the If statement would be used in this case.
The syntax of an if statement is:
if ( <condition> ) {
    <statements>
}
The syntax of an if-else statement is:
if ( <condition> ) {
    <statements #1>
} else {
    <statements #2>
}
The must produce a Boolean result. If it is true, the statement(s) are executed. The must produce a Boolean result. If it is true, the statements #1 are executed. If it is false, the statements #2 are executed.
Example:
if (temperature > 0) {
    Console.print("Above freezing");
}
Example:
if (age < 18) {
    Console.print("Too young to vote.");
} else {
    Console.print("Old enough to vote!");
}
 
Did you know icon
  • The condition must be placed inside parentheses "()"
  • Notice that both forms of the "if" statement DO NOT end with a semicolon!
  • Also note the curly brackets used to denote the code inside the selection structure.
  • The body of a selection statement should be indented.
  • An open curly brace "{" should be placed on the same line as the if statement, and the closing curly brace "}" should be on a separate line and aligned with the if statement
  • If there is an else statement, it should have the closing curly brace "}" and the opening curly brace "{" on the same line

Questions Icon Check Your Understanding

  1. Which output statement will be displayed in the Console?

    boolean socksOn = false;
    
    if (socksOn) {
        Console.print("Put shoes on.");
    } else {
        Console.print("Put socks on.");
    }
    Answer Button Answer
     
  2. Which output statement will be displayed in the Console?

    int numStudents = 30;
    
    if (numStudents > 25) {
         Console.print("The number of students is greater than 25.");
    } else {
         Console.print("The number of students is less than or equal to 25.");
    }
    Answer Button Answer

The Else-If Statement

Suppose you wanted to choose from a set of alternatives and not from just two alternatives. An else-if statement could handle the choices.

The syntax of an else-if statement is:

if ( <condition #1> ) {
    <statements #1>
} else if ( <condition #2> ) {
    <statements #2>
} else {
    <statements #3>
}

Each condition must produce a Boolean result. The FIRST condition to evaluate to true will cause its block of code to execute. If none of the conditions evaluate to true, the code in the else block is execute.

Example:

if (guess == SECRET_NUM) {		//correct
    Console.print("You guessed it!");
} else if (guess < SECRET_NUM) {	//too low
    Console.print("Too low.");
} else {				//too high
    Console.print("Too high.");
}

Note that if a condition is true then only the statements with that condition are executed. None of the other conditions are tested or executed. This is important to keep in mind while choosing the order in which to create your condition statements! The order of your expressions is important because it can affect what statements are executed.

Questions Icon Check Your Understanding

  1. Suppose you wanted to write a selection structure to assign a student a level based on their percentage. Can you spot the problem with the following block of code? How could you rewrite it so it will work properly?

    if (mark > 50) {
        grade = "Level 1";
    } else if (mark > 60) {
        grade = "Level 2";
    } else if (mark > 70) {
        grade = "Level 3";
    } else if (mark > 80) {
        grade = "Level 4";
    } else {
        grade = "Below Level 1";
    }
    
    Answer Button Answer
  2. Which output statement will be displayed in the Console?

    double bankBalance = 50;
    
    if (bankBalance > 100) {
         Console.print("There is more than $100.00 in this bank account.");
    } else if (bankBalance > 0) {
         Console.print("There is $100.00 or less in this bank account.");
    } else {
         Console.print("There are no funds available in this account");
    }
    
    Answer Button Answer

Nested If Statements

A nested if statement refers to an if statement inside another one. Take a look at the following example

if (gradeLevel == 10) {
    if (homeroom == 100) {
        Console.print("You are in Homeroom 100.");
    } else {
        Console.print("Your Homeroom is not listed in Grade 10.");
    }
}

The only way the homeroom == 100 condition is evaluated is if gradeLevel is equal to 10, otherwise it is completely skipped. If gradeLevel is equal to 10, then the program will evaluate the code inside this statement.

The Switch Statement

The switch statement is a conditional control structure that uses the result of an expression to determine which statement to execute. The switch statement is sometimes preferable to the else-if statement because code may be easier to read.

The syntax of a switch statement is:

switch (<expression>) {
    case x:
        <statements>		//these statements will run when expression equals x
        break;
    case y:
        <statements>		//these statements will run when expression equals y
        break;
    ...				//may be multiple clauses
    default:			//optional, executed when none of the cases are met
        <statements>
        break;
}

The expression must evaluate to either an int or char data type (not double). If you are using JDK 7 or later, you can also use a String expression for the switch statement.

Here is an example of a switch statement:

switch (standing) {
    case 1:
        Console.print("Gold Medal");
        break;
    case 2:
        Console.print("Silver Medal");
        break;
    case 3:
        Console.print("Bronze Medal");
        break;
    default:
        Console.print("Certificate of Participation");
        break;
}

It is good practice to include a default case that will execute if none of the case statements match the expression. Each case statement should end with a break statement which prevents a fall-through error. When a case falls through, it executes the code in the next case statement. This can be useful when the same set of statements applies to more than one situation.

Questions Icon Check Your Understanding

  1. Can you tell which output statement will be displayed in the console when score contains the value 3? What about a score of 6?

    switch (score) {
        case 0:
            Console.print("Better luck next time.");
            break;
        case 1:
        case 2:
        case 3:
        case 4:
        case 5:
            Console.print("Pretty good.");
            break;
        case 6:
        case 7:
        case 8:
        case 9:
        case 10:
            Console.print("Good!");
            break;
        default:
            Console.print("Out of range");
            break;
    }
    Answer Button Answer

Introducing the Debug Perspective

Debugging is the process of getting an application to work correctly (removing program 'bugs' - bits of code that do not work as intended.) Many IDEs contain tools that help the debugging process.

A very simple way to debug code is to add additional Console.print() statements to an application to help detect logic errors. You can place these statements just after a variable is assigned a new value, or before and after a condition to help detect a logic error.

Another simple option is to comment out code to narrow down which part of the program is causing an issue. You can select a block of code and select Source -> Toggle Comment (or Ctrl+/) to block out a large section of code all at once. Perform to same action again to un-comment (but make sure you have selected the same block of code!)

Eclipse offers a perspective that is helpful for finding logical errors, called the "Debug" perspective. To open the debug perspective, click the "Open Perspective" toolbar button at the upper right corner of Eclipse.

A dialog box with a list of available perspectives will open; select Debug from the list. When the Debug perspective opens, it should resemble this:

Notice that the screen is now divided into five different sections. The most important one is the "Variables" window in the upper right corner. This will allow you to view the contents of all the variables in your program, as it is running. The Variables are listed in the order that they are declared, and become highlighted when their values change.

Since computers run so quickly, we need to slow down the program execution to allow us to view the contents of our variables, and to observe the flow of our code. One way to accomplish this is by using a breakpoint, which signals to the interpreter that code execution should stop at this point, and give the programmer the option of 'stepping' through the code, one line at a time. Stepping though code and watching the values of variables can be an effective way to determine logic errors

To place a breakpoint in a program, find an executable line of code (not a comment or a whitespace line) and select Run -> Toggle Breakpoint (or type Ctrl+Shift+B). A blue circle should appear to the left of that line of code.

Instead of clicking the run button, click the debug button just beside it: debug button. When your program reaches the line with the breakpoint, the program will pause. You will be able to view the contents of your variables, and then either resume your code (run it again, until it reaches another breakpoint) or step through one line at a time.

Here is a screenshot of a program in the middle of execution:

The execution control toolbar buttons can be used to control the running of your program, one line at a time. Below is a quick description of the important buttons:

Evidence of Learning


Programming Exercises

Once you have read the material above complete the following activities. Place all your classes in the activity4 package (If a question asks you to modify a program, you must create a NEW copy of the class inside the activity4 package; do not change the code for the original program!)

  1. Modify the CircleCircumference application from activity 2 to prompt the user for the radius. If a negative number is entered by the user for the radius value, the program should display the message “Negative radii are illegal”. Otherwise, the application should calculate and display the circumference of the circle.
  2. Create a SurfsUp application that prompts the user for the wave height and then displays “Great day for surfing” when the waves are 6 feet or over, “Go body boarding!” when the waves are between 3 and 6 feet, and “Go for a swim.” when the waves are 3 feet or less. If the user enters a negative number, your program will display “Whoa! What kind of surf is that?”
  3. The Saffir-Simpson Hurricane Scale provides a rating (a category) depending on the current intensity of a hurricane. Create a Hurricane application that displays the wind speed, in km/h, for the hurricane category entered by the user. Refer to this website for the hurricane levels. Use a switch statement to create this application.
  4. In mathematics, the quantity b2-4ac is called the “discriminant”.  Create a Discriminant application that prompts the user for the values of a, b, and c and then displays “No roots” if the discriminant is negative, “One root” if the discriminant is zero, and “Two roots” if the discriminant is positive.  Application output should look similar to:
          Enter the value for a: 7
          Enter the value for b: -9
          Enter the value for c: 2
          Two roots
Commit your progress to GitHub every day. You are getting assessed on the frequency of your commits, and the quality of your commit messages! Submit the Hapara evidence card for your teacher to leave you feedback on your code.