1 / 9

Running Totals

Running Totals. CSIS 1595: Fundamentals of Programming and P roblem 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

ariane
Download Presentation

Running Totals

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


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

  2. 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

  3. 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

  4. Trip Mileage Example

  5. 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) • Doublepennies each time through loop by multiplying by 2 • pennies *= 2 • Since we know how many squares there are, we can use a for loopfrom 1 to 65

  6. Running Products

  7. 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

  8. 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 firststudent • Initialize highest name, grade to those values

  9. Running Maximums/Minimums

More Related