Decision Making
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:
|
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?