Decision Making
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");