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

                If the condition is true, the answer to the question is “yes.” If the condition is false, the answer to the question is “no.” Given the flowchart in Figure 2.8, try to write a pseudo- code version of the cut-CEO-salary-in-half algorithm. When you’re done, compare your answer to our answer:
print “Enter CEO Salary: ”
input ceoSalary
if ceoSalary is greater than 500000
set ceoSalary to ceoSalary * 0.5
print “Reduced CEO Salary is $” ceoSalary
Practice Problems with Pseudocode Only
Everybody knows the saying, a picture is worth a thousand words. This may be true, but compare the space consumed by and the effort to construct Figure 2.8’s flowchart with the space consumed by and the effort to write the corresponding pseudocode. Pictures help you get started, but text is more efficient once you know what you’re doing. So now let’s try skipping the flowchart and going immediately to pseudocode.
First, let’s write an algorithm that prints “No school!” if the temperature is below 0 degrees. Which if statement form should you use for this problem? Since the problem description says to do either something or nothing, you should use the simple “if” form:
2.7 if Statements 35
   print “Enter a temperature: ” input temperature
if temperature is less than 0
print “No school!”Apago PDF Enhancer
Next, let’s write an algorithm that prints “warm” if the temperature is above 50 degrees and prints “cold” otherwise. Which if statement form should we use? Since the problem description says to do one thing or another thing, you should use the “if, else” form:
print “Enter a temperature: ”
input temperature
if temperature is greater than 50
print “warm” else
print “cold”
Finally, let’s write an algorithm that prints “hot” if the temperature is above 80 degrees, prints “OK” if it’s between 50 and 80 degrees, and prints “cold” if it’s less than 50 degrees. For this problem, it’s appropri- ate to use the “if, else if” form, like this:
print “Enter a temperature: ”
input temperature
if temperature is greater than 80
print “hot”
else if temperature greater than or equal to 50
print “OK” else
print “cold”
Practice writing a pseudocode algorithm.







































































   67   68   69   70   71