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;
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 < 0num is less than zero.
- The
ifstatment 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?