Page 68 - Introduction to Programming with Java: A Problem Solving Approach
P. 68

                34 Chapter 2 Algorithms and Design
What happens if the grade is 85? The print “A” statement is skipped, and the print “B” statement is ex- ecuted. Once one of the conditions is found to be true, then the rest of the entire if statement is skipped. So the third, fourth, and fifth print statements are not executed.
What happens if all of the conditions are false? If all of the conditions are false, then the subordinate statement under “else” is executed. So if the grade is 55, print “F” is executed. Note that you’re not required to have an “else” with the “if, else if” statement. If you don’t have an “else” and all of the conditions are false, then no statements are executed.
if Statement Summary
            Use the way that fits best.
Use the first form (“if”) for problems where you want to do one thing or nothing. Use the second form (“if, else”) for problems where you want to do either one thing or an- other thing. Use the third form (“if, else if”) for problems where there are three or more possibilities.
Practice Problem with Flowchart and Pseudocode
Let’s practice what you’ve learned about if statements by presenting a flowchart and having you write the corresponding pseudocode for an algorithm that cuts a CEO’s excessively large salary in half. Figure 2.8 presents the flowchart.
     Apago PDF Enhancer
print “Enter CEO Salary:”
ceoSalary
greater than
$500,000 ?
no yes
     Figure 2.8
Flowchart for reducing CEO salaries
input ceoSalary
set ceoSalary to ceoSalary * 0.5
 print “Reduced CEO Salary is $” ceoSalary
In flowcharts, we omit the word “if” from the condition in diamonds and add a question mark to turn the condition into a question. The question format fits well with the “yes” and “no” on the exiting arrows.















































































   66   67   68   69   70