Running Totals CSIS 1595: Fundamentals of Programming and Problem Solving 1.
-
Upload
heather-hunt -
Category
Documents
-
view
216 -
download
1
Transcript of Running Totals CSIS 1595: Fundamentals of Programming and Problem Solving 1.
Running Totals
CSIS 1595: Fundamentals of Programming and Problem Solving 1
Running Totals
• Goal: Creating a cumulative value based on data entered/computed by program– Generally done with a loop
• Algorithm:– “Accumulator” variable kept– Initialize accumulator to value before any data– Each time through loop, update accumulator based on
current data in terms of:• Current data• Previous value of accumulator
Trip Mileage Example
• Goal: Keep track of total mileage driven on trip
• Algorithm:– Prompt user for mileage this stage– Increment total mileage by amount entered by user each
stage– Initially: total mileage = 0– Use sentinel loop to decide when to quit
Trip Mileage Example
Running Products
• Can increment running totals in ways other than addition• Example: – Place a penny on first square of chess board– Double number of pennies on each subsequent square– How many pennies on each square?
• Design:– Initial value of pennies = 1 (number on first square)– Double pennies each time through loop by multiplying by 2• pennies *= 2
– Since we know how many squares there are, we can use a for loop from 1 to 65
Running Products
Running Maximums/Minimums
• May want to find largest/smallest/etc. in some list of values• Example:– User enters names and corresponding grades– Program then prints name of student with highest grade
Running Maximums/Minimums
• Key idea: Each time through loop, keep track of:– Highest grade so far– Name of student with the highest grade so far
• Modifying accumulators in loop:– Prompt for name, grade of next student– Compare their grade with highest grade so far– If the new grade is higher:• The highest grade so far is the new grade• The student with the highest grade is the new name
• Initialization:– Prompt for name, grade of first student– Initialize highest name, grade to those values
Running Maximums/Minimums