Decision Making

Site: Saylor Academy
Course: CS101: Introduction to Computer Science I
Book: Decision Making
Printed by: Guest user
Date: Thursday, June 13, 2024, 6:36 PM

Description

Read this chapter, which reviews how computers make decisions using if statements. As you read this tutorial, you will understand that sometimes it is important to evaluate the value of an expression and perform a task if the value comes out to be true and another task if it is false. In particular, try the simulated program under the heading "Simulated Program" to see how a different response is presented to the user based on if a number is positive or negative.

Pay special attention to the "More Than One Statement per Branch" header to learn how the 'else' statement is used when there is more than one choice.

1. Decision Making

lightning

This chapter looks at how computer programs make decisions using the if statement. This statement is one of the fundamental building blocks of programming.

Chapter Topics:

      • Two-way Decisions
      • The if statement
      • Outline of a two-way decision
      • Blocks of statements
      • Boolean Expressions
      • Relational Operators
      • Example Programs


Question 1:

You are driving in your car and it starts to rain. The rain falls on your windshield and makes
it hard to see. Should your windshield wipers be on or off?


Source: Bradley Kjell, http://programmedlessons.org/Java9/chap16/ch16_01.html
Creative Commons License This work is licensed under a Creative Commons Attribution-NonCommercial 4.0 License.

2. Two-way Decisions


Answer:

On.

Two-way Decisions

TwoWay

The windshield wipers are controlled with an ON-OFF switch. The flowchart at right shows how this decision is made.

Start at the top of the chart then follow the line to the question:

is it raining?

The answer is either true or false.

      • If the answer is true,
        • follow the line labeled True,
        • perform the instructions in the box "wipers on",
        • follow the line to "continue".
  • If the answer is false,
        • follow the line labeled False,
        • perform the instructions in the box "wipers off",
        • follow the line to "continue".


Question 2:

How many ways can you go from "start" to "continue"?

3. Decisions


Answer:

Two.

Decisions

The windshield wiper decision is a two-way decision (sometimes called a binary decision). The decision seems small, but in programming, complicated decisions are made of many small decisions. Here is a program that implements the wiper decision:

import java.util.Scanner;
public class RainTester
{
  public static void main (String[] args) 
  {
    Scanner scan = new Scanner( System.in );
    String answer;

    System.out.print("Is it raining? (Y or N): ");
    answer =  scan.nextLine();
    
    if ( answer.equals("Y") )                // is answer exactly "Y" ?              
      System.out.println("Wipers On");              // true branch
    else
      System.out.println("Wipers Off");             // false branch   
  }
}


The user is prompted to answer with a single character, Y or N :

System.out.print("Is it raining? (Y or N): ");

The Scanner reads in whatever the user enters (even if the user enters more than one character):

answer =  scan.nextLine();

The if statement tests if the user entered exactly the character Y (and nothing else):

if ( answer.equals("Y") )  // is answer exactly "Y" ?              

If so, then the statement labeled "true branch" is executed. Otherwise, the statement labeled "false branch" is executed.

The "true branch" is separated from the "false branch" by the reserved word else.

Indenting: Indent the "true branch" and "false branch" one level in from the if and else. This makes it easier for a human (you) to see the logic of the program. However, the compiler ignores indenting.

Sensible indenting and program layout is important. You want to make it as clear as possible what a program is doing. Often CS departments in schools and industry have formatting standards. It is important to be consistent. Use the same number of spaces every time you indent. Often, programmers use two, three, or four spaces.

Withoutproperuseofspaceandindentsseeingthelogicandunderstandingaprogramsometimesbecomesveryhard.


Question 3:

What happens if the user enters anything other than exactly the character Y ?

4. Checking a String


Answer:

If the user enters anything other than exactly the single character Y then the "false branch" is executed.

Checking a String

rainProgram

The if statement

if ( answer.equals("Y") )            

picks either the "true branch" or the "false branch" . Only one branch or the other is executed, just as in the flow chart. This part of the statement

answer.equals("Y")           

evaluates to true if the string referenced by answer contains exactly the single character "Y" . For anything else it evaluates to false. This is somewhat awkward. Dealing with user input is often awkward. Later on you will see better ways to do this. Here are some runs of the program:

C:\Examples>javac RainTester.java

C:\Examples>java RainTester
Is it raining? (Y or N): Y
Wipers On

C:\Examples>java RainTester
Is it raining? (Y or N): N
Wipers Off

C:\Examples>java RainTester
Is it raining? (Y or N): Yes
Wipers Off

C:\Examples>java RainTester
Is it raining? (Y or N): Rats
Wipers Off


Question 4:

Is the integer -12 negative or not?

5. Number Tester


Answer:

-12 is negative.

Number Tester

TwoWay2

An integer may be negative, or not. If it is not negative, then it is positive or zero. Here is that idea expressed as a flow chart:

The diamond box shows a two-way decision. Either the false branch or the true branch is taken depending on whether

num < 0

is true or false.

The "two-way split" of the program is easy to see in a two dimensional chart. It is harder to see this in a program where line follows line one after another. The flow chart shows the overall logic of the program. Most of the details of syntax are left out. It is often helpful to sketch a flowchart when you are designing a program. You can use the flowchart to get the logic correct, then fill in the details when you write the program.


Question 5:

The user runs the program and enters "12". What will the program print?

6. The Program


Answer:

    Enter an integer: 12 The number 12 is zero or positive Good-bye for now

The false branch is executed because the answer to the question num < 0 was false.

The Program


Here is the number tester implemented as a program:

import java.util.Scanner;

public class NumberTester
{
  public static void main (String[] args) 
  {
    Scanner scan = new Scanner( System.in );
    int num;

    System.out.println("Enter an integer:");
    num = scan.nextInt();
    
    if ( num < 0 )                
      System.out.println("The number " + num + " is negative"); 
    else
      System.out.println("The number " + num + " is zero or positive"); 
    
    System.out.println("Good-bye for now"); 
  }
}

The words if and else are markers that divide the decision into two sections. The else divides the true branch from the false branch. The if is followed by a question enclosed in parentheses. The expression num < 0 asks if the value in num is less than zero.

      • The if statement always asks a question (often about a variable).
      • If the answer is true only the true branch is executed.
      • If the answer is false only the false branch is executed.
      • No matter which branch is chosen, execution continues with the statement after the false branch.

Notice that a two-way decision is like picking which of two roads to take to the same destination. The fork in the road is the if statement, and the two roads come together just after the false branch.


Question 6:

The user runs the program and enters -5. What will the program print?

7. Simulated Program


Answer:

    Enter an integer: 12 The number 12 is zero or positive Good-bye for now

Only the true-branch was executed because the answer to the question num < 0 was true.

Simulated Program


Here is a simulation of this program (using JavaScript so it runs in your browser). Of course, for maximum benefit copy the program to a file and run it. But, play with the following if you want. Perform the steps 1, 2, and 3 under the simulated monitor as many times as you want. (Note: if this does not work, your browser does not have JavaScript enabled. Skip this and go on to the next page.)


import java.util.Scanner;

public class NumberTester
{
  public static void main (String[] args) 
  {
    Scanner scan = new Scanner( System.in );
    int num;

    System.out.println("Enter an integer:");
    num = scan.nextInt();
    
    if ( num < 0 )                
      System.out.println("The number " +
           num + " is negative"); 
    else
      System.out.println("The number " + 
           num + " is zero or positive"); 
    
    System.out.println("Good-bye for now"); 
  }
}
        Simulated Monitor





2. Click in the "monitor" window after the last line and enter a number


This is just a simulation (using JavaScript), so it is not exactly like a compiling and running a real Java program. Don't take it too seriously. Please do the real thing if you can. Try this on-line compiler: http://ideone.com/ if you don't mind a few ads.

Question 7:

Try the program (or look at the flowchart) with the value 0 (zero). What is the output?

8. More than one Statement per Branch


Answer:

    Enter an integer:
    0
    The number 0 is zero or positive
    Good-bye for now

Zero is neither negative nor positive, (although often programs treat zero as if it were positive).
It would be nice to treat it as a separate case. This problem will be fixed in a few pages.

More than one Statement per Branch


Here is the program again with some added statements:

import java.util.Scanner;

public class NumberTester
{
  public static void main (String[] args)
  {
    Scanner scan = new Scanner( System.in );
    int num;

    System.out.println("Enter an integer:");
    num = scan.nextInt();

    if ( num < 0 )
    {
      System.out.println("The number " + num + " is negative.");   // true-branch
      System.out.println("Negative numbers are less than zero.");  // true-branch
    } 
    else
    {
      System.out.println("The number " + num +                     // false-branch
        " is zero or positive.");                                  // false-branch
      System.out.print  ("Positive numbers are greater ");         // false-branch
      System.out.println("than zero. ");                           // false-branch
    }

    System.out.println("Good-bye for now");    // always executed
  }
}

To include more than one statement in a branch, enclose the statements with braces, { and }. A group of statements grouped together like this is called a block statement, (or usually, just block).

There can be as many statements as you want in a block. A block can go any place a single statement can go. All the statements in the true block are executed when the answer to the question is true.

Of course, all the statements in the false block are executed when the answer to the question is false. The false block consists of the block that follows the else. Notice that the very last statement in the program is not part of the false block.

Indenting: Indent all the statements in a block to the same level. If a statement takes more than one line, the additional lines are further indented. In these notes, braces each have their own line and are indented to the same level as the if and else. But different coding standards call for different formats. It is important to be consistent.


Question 8:

The user enters a 17. What will the new program print?

9. Outline of a Two-way Decision


Answer:

    Enter an integer:
    17
    The number 17 is zero or positive.
    Positive numbers are greater than zero.
    Good-bye for now

The false block was executed because the answer to the question (num < 0) was false.
The false block consists of three statements.

Outline of a Two-way Decision


Here is an outline of a two-way decision structure:

// statements that are executed before the decision

if ( condition )
// true branch

else
// false branch

// statements that are executed after the branches join together again

Here are some details:

      • The condition evaluates to true or false, often by comparing variables and values.
      • The else divides the true branch from the false branch.
      • The statements after the false branch are always executed.
      • A block consists of several statements inside a pair of braces, { and }.
      • The true branch can be a block.
      • The false branch can be a block.
      • There can be as many statements in a block as you need.
      • When a block is chosen for execution, the statements in it are executed one by one.

The condition can compare what is held in a variable to other values. You can use the comparisons <>, and so on. (More about these later.) The first statement after the false branch will be executed no matter which branch is chosen. The if-else is like a fork in the road, but the road always comes together again.


Question 9:

Is the following section of a program correct?

    if ( num < 0 ) System.out.println("The number " + num + " is negative."); else System.out.println("The number " + num + " is zero or positive."); System.out.print ("Positive numbers are greater "); System.out.println("than zero. "); System.out.println("Good-bye for now");

10. Only One Statement per Branch


Answer:

No. The programmer probably wants the three statements after the else to be part of a false block,
but has not used braces to show this.

Only One Statement per Branch

The false block was not put inside braces:

if ( num < 0 )
    System.out.println("The number " + num + " is negative.");   
else
    System.out.println("The number " + num + " is zero or positive.");  
    System.out.print  ("Positive numbers are greater ");  
    System.out.println("than zero. ");    

System.out.println("Good-bye for now");  

Our human-friendly indenting shows what we want, but the compiler ignores indenting. The compiler groups statements according to the braces. What it sees is the same as this:

if ( num < 0 )
System.out.println("The number " + num + " is negative."); // true-branch
else
System.out.println("The number " + num + " is zero or positive"); // false-branch
System.out.print ("Positive numbers are greater "); // always executed
System.out.println("or equal to zero. "); // always executed
System.out.println("Good-bye for now"); // always executed

The compiler expects a single statement to follow the if and a single statement to follow the else. However, a block statement works as a single statement.


Question 10:

How would you fix the problem?

11. Practice


Answer:

    if ( num < 0 ) System.out.println("The number " + num + " is negative."); // true-branch else { System.out.println("The number " + num + " is zero or positive"); // false-branch System.out.print ("Positive numbers are greater "); // false-branch System.out.println("or equal to zero. "); // false-branch } System.out.println("Good-bye for now"); // always executed

The true branch has one statement. The false branch has one statement, a block containing three statements.

Practice

At a movie theater box office a person less than age 13 is charged the "child rate". Otherwise a person is charged the "adult rate." Here is a partially complete program that does this:

import java.util.Scanner;
public class BoxOffice
{
  public static void main (String[] args) 
  {
    Scanner scan = new Scanner( System.in );
    int age;
 
    System.out.println("Enter your age:");
    age = scan.nextInt();

    if (  )
    {
      System.out.println("Child rate.");   
    } 
    else
    {
      System.out.println("Adult rate.");   
    }
    System.out.println("Enjoy the show.");    // always executed
  }
}

In this program, the true branch and the false branch are both blocks. Each block contains only one statement, but this is OK. Often programmers do this for clarity.

Question 11:

Fill in the blank so that a person under the age of 13 is charged the child rate.

12. Box Office Program


Answer:

if ( age < 13  )

Box Office Program

Here is the program with the blank filled in correctly:

import java.util.Scanner;
public class BoxOffice
{
  public static void main (String[] args) 
  {
    Scanner scan = new Scanner( System.in );
    int age;
 
    System.out.println("Enter your age:");
    age = scan.nextInt();

    if ( age < 13  )
    {
      System.out.println("Child rate.");   
    } 
    else
    {
      System.out.println("Adult rate.");   
    }
    System.out.println("Enjoy the show.");    
  }
}

Here is what happens for one run of the program:

  1. The program prints "Enter your age".
  2. The user enters an age: "21", for example.
  3. The string "21" is converted from characters into an int and put into the variable age.
  4. The condition age < 13 is tested.
  5. 21 < 13 is false.
  6. The false branch is executed: the program prints "adult rate".
  7. Execution continues with the statement after the false branch: "Enjoy the show" is printed.


Question 12:

What does the program output if the user enters 11?

13. Boolean Expressions


Answer:

    Enter your age
    11
    Child rate
    Enjoy the show

Boolean Expressions


Relational Operators
Operator
Meaning
A == B
is A equal to B ?
A < B
is A less than B ?
A <= B
is A less than or equal to B ?
A > B
is A Greater than B ?
A >= B
is A Greater than or equal to B ?
A != B
is A not equal to B ?


We need to look at the condition part of the if statement. Usually this is a boolean expression. Recall that an expression is is a combination of literals, operators, variable names, and parentheses used to calculate a value.

Annotation 2020-03-08 215302

Boolean expressions often compare numbers. A relational operator says how the numbers are compared.

Here are some annoying details (that will be really annoying later on if you forget about them):

      • The operator for "equal" is   ==   (two equal signs in a row). In your web browser it may be hard to see that there are two equal signs.
      • The operator for "not equal" is   !=   (exclamation point equal sign).

It is easy to forget these two details, and easy to overlook these details in a program. You might spend hours debugging a program because a   =   was used where a   ==   belongs.



Question 13:

Fill in the blanks in the following chart:

Expression
Value
Expression
Value
25 == 25
25 != 25
25 <= 25
25 > 25
25 >= 25
25 = 25
-5 < 7
-305 <= 97

14. Using Boolean Expressions


Answer:

Expression
Value
Expression
Value
25 == 25
true
25 != 25
false
25 <= 25
true
25 > 25
false
25 >= 25
true
25 = 25
illegal
-5 < 7
true
-305 <= 97
true

Using Boolean Expressions

In an if statement, the true or false  of a boolean expression picks whether the true branch or the false branch is executed. Look at another story problem:

A store wants a program that calculates the tax on an item of clothing. An item that costs $100 or more has a 5% tax. An item that costs less than $100 is tax free. Write a program that asks for a price, then calculates and prints the tax, then prints the total cost.

Here is the program, not quite finished:

 

public class TaxProgram
{
  public static void main (String[] args) 
  {
     
    
     
    
    double price;
    double tax ;

    System.out.println("Enter the price:");
    
          

    if (   )

         

    else
       

    System.out.println("Item cost: " + price + " Tax: " + tax + " Total: " + (price+tax) );    
  }
}

Here are some program fragments to use in completing the program. Use your mouse to copy-and-paste them into the program.

tax = price * taxRate;          Scanner scan = new Scanner( System.in );
price = scan.nextDouble();      final double taxRate = 0.05;
price >= 100.0                  import java.util.Scanner;
tax = 0.0;

(Of course, it would be nice to copy the program to a file, enter your corrections and run the program.)


Question 14:

Complete the program by filling in the blanks.

15. Adding in a Zero


Answer:

The answer is given below:

Adding in a Zero

Here is the complete program.

import java.util.Scanner;
public class TaxProgram
{
  public static void main (String[] args)
  {
    final double taxRate = 0.05;
    Scanner scan = new Scanner( System.in );
    double price;
    double tax ;

    System.out.println("Enter the price:");
    price  = scan.nextDouble();     

    if ( price >= 100.0  )
      tax = price * taxRate;   
    else
      tax = 0.0;

    System.out.println("Item cost: " + price + " Tax: " + tax + " Total: " + (price+tax) );    
  }
}

Is the logic of the program is correct? The expression (price+tax) in the last statement sometimes adds zero to price. This is fine. Adding zero does not change the result.


Question 15:

The user buys a shirt for $100 What will be printed on the monitor?

16. Three-way Decisions


Answer:

    Enter the price: 100 Item cost: 100 Tax: 5.0 Total: 105.0

Three-way Decisions

An if statement makes a two-way decision. Surely you must sometimes pick from more than just two branches?

We ran into this problem with a previous example program that divided integers into negative and non-negative. It really should pick one of three choices:

      • Negative: ... -3 -2 -1
      • Zero: 0
      • Positive: +1 +2 +3 ...

Two-way decisions can do this. First divide the integers into two groups (using a two-way decision):

      • Negative: ... -3 -2 -1
      • Zero and Positive: 0 +1 +2 +3 ...

Then further divide the second group (by using another two-way decision):

      • Negative: ... -3 -2 -1
      • Zero and Positive:
        • Zero: 0
        • Positive: +1 +2 +3 ...

By repeatedly splitting groups into subgroups, you can split a collection into any number of fine divisions.


Question 16:

How could you divide a group of people into:

  • children
  • male adults
  • female adults

17. Flowchart


Answer:

You could first divide the group into:

    1. children
    2. adults

And then divide the adults into:

    1. male adults
    2. female adults

Flowchart

We wish to perform two splits to divide integers into negative, zero, and positive. First zero and positives are split from the negatives, and then that group is further split.

ThreeWay

The flowchart shows how this works. One decision is nested inside the false branch of the first decision. A negative integer is correctly detected by the first decision. But a zero or positive integer goes through another decision to pick the correct category for it.

Question 17:

Are there other ways to do this?

18. Number Tester Program


Answer:

Yes. There are ways to arrange the tests. You could first split the group into zero and not-zero.
Then split not-zero into positive and negative. But you will always need two tests, whatever they are.

Number Tester Program

Here is a program that implements the flowchart. The part that corresponds to the nested decision of the flow chart is in red. This is called a nested if statement because it is nested in a branch of an outer if statement.

Indenting: The "false branch" of the first if is a complete if statement. Its two branches are indented relative to the if they belong to.

import java.util.Scanner;

public class NumberTester
{
  public static void main (String[] args)  
  {
    Scanner scan = new Scanner( System.in );
    int num;

    System.out.println("Enter an integer:");
    num = scan.nextInt();

    if ( num < 0 )
    {
      // true-branch
      System.out.println("The number " + num + " is negative");

    } 
    else
    { 
      // nested if
      if ( num > 0 )
      { 
        System.out.println("The number " + num + " is positive"); 
      } 
      else
      {
        System.out.println("The number " + num + " is zero");
      } 

    }

    System.out.println("Good-bye for now");    // always executed
  }
}


Question 18:

Could an if statement be nested inside the true branch of another if statement?

19. Last Page


Answer:

Yes. And you can have two nested if statements, one per branch.

Last Page

This is the end of the chapter.
If you want, 
  review the following topics;
else, 
  go on to the next chapter.