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.
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?