Page 84 - Introduction to Programming with Java: A Problem Solving Approach
P. 84
50
Chapter 2 Algorithms and Design
sort assets by priority
set totalAnnualReserve to 0 while another asset exists
print assetName
input activity
input yearsAhead
input dollarCost
set annualReserve to dollarCost / yearsAhead
set totalAnnualReserve to totalAnnualReserve annualReserve
print totalAnnualReserve
Again, the algorithm does not include prompts. You’ll deal with all those details later.
For step 4, you identify the three variables, totalAnnualReserve, currentNetIncome, and additionalIncome. For this you need to get someone in the accounting department to provide a value for currentNetIncome. Then have the program subtract it from the totalAnnualReserve com- puted in step 3 to obtain the additionalIncome required to make the plan work. Oh yes! If the answer comes out negative, you’ll want it to just print zero to indicate that your city won’t have to come up with any
additional income. Here’s a pseudocode description of the implementation of step 4:
input currentNetIncome
set additionalIncome to currentNetIncome totalAnnualReserve if additionalIncome is less than 0
set additionalIncome to 0
Apago PDF Enhancer
print “Additional income needed = ” additionalIncome
OK, that’s probably enough preparation for next week’s city council meeting. At least you’ll be able to give
the council members a reasonable feeling for the amount of work required.
Summary
• Use pseudocode to write informal descriptions of algorithms. Use understandable names for variables. Indent subordinate statements.
• When your program needs an input, provide an informative prompt to tell the user what kind of infor- mation to supply.
• A flowchart provides a visual picture of how the elements of a program are related and how control flows through those elements as the program executes.
• There are three basic well-structured flow-of-control patterns—sequential, conditional, and looping.
• You can implement conditional execution using the three forms of the if statement: “if,” “if, else,” and
“if, else if.”
• Provide all loops with some kind of terminating condition such as counter, user query, or sentinel
value.
• Use a nested loop if there’s a need to repeat something during each iteration of an outer loop.
• Use tracing to (1) obtain an intimate understanding of what an algorithm does and (2) debug programs
that have logical errors.
• Use more abstract language to describe larger and more complex programming operations succinctly.