running totals csis 1595: fundamentals of programming and problem solving 1

9
Running Totals CSIS 1595: Fundamentals of Programming and Problem Solving 1

Upload: heather-hunt

Post on 18-Jan-2016

218 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Running Totals CSIS 1595: Fundamentals of Programming and Problem Solving 1

Running Totals

CSIS 1595: Fundamentals of Programming and Problem Solving 1

Page 2: 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

Page 3: Running Totals CSIS 1595: Fundamentals of Programming and Problem Solving 1

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

Page 4: Running Totals CSIS 1595: Fundamentals of Programming and Problem Solving 1

Trip Mileage Example

Page 5: Running Totals CSIS 1595: Fundamentals of Programming and Problem Solving 1

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

Page 6: Running Totals CSIS 1595: Fundamentals of Programming and Problem Solving 1

Running Products

Page 7: Running Totals CSIS 1595: Fundamentals of Programming and Problem Solving 1

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

Page 8: Running Totals CSIS 1595: Fundamentals of Programming and Problem Solving 1

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

Page 9: Running Totals CSIS 1595: Fundamentals of Programming and Problem Solving 1

Running Maximums/Minimums