Finding the total, average, minimum and maximum in a program
Archive - Originally posted on "The Horse's Mouth" - 2012-02-22 08:53:29 - Graham Ellis
There are a number of programming techniques which the experienced coder takes for granted, but which aren't necessarily intuitive for the newcomer. Call them "design techniques" or "design patterns" that need to be learned, if you want some fashionable buzzwords.
• To produce the sum of a stream / flow / collection of values, initialise a variable to zero, loop through each of the values adding it into that variable, and when you reach the end of the loop the variable contains the total.
• To produce the average of a stream / flow / collection of values, write a loop just as you did to calculate the total. In a addition, start a second variable (a counter) at 0 and add 1 to each each time to add a value to your running total variable. When you have completed the loop, divide the total by the number of values that made up that total. If you are counting integers (whole numbers), remember that your average might not be a whole number and so you'll need to convert to a real / floating point number to get an accurate average.
• To find the smallest of a stream / flow / collection of values, write a loop to go through all of those values. The first time through the loop, set a variable which is the minimum so far to the first value. On subsequent times through the loop, compare the minimum value (so far) with the incoming value, and save the incoming value as the minimum value (so far) if it's the smaller. When you reach the end of the loop, you have the minimum value.
• To find the largest of a stream / flow / collection, use the same principle as you used for the minimum, but check to see if the incoming value is great and if it is, save it as the maximum so far.
Newcomers are often tempted to start loops to find the maximum value at zero to avoid the first time check in the loop. Don't do that!. If you have a file of the temperatures in Spitzbergen, where it never gets above zero in winter, you'll end up with a result that tells you the maximum was zero, rather than the chilly -5.4 which happened to be the least negative of all the numbers in the incoming data.
There's an example of each of these algorithms, implemented within the same program in Ruby [here] on our web site - from yesterday's Learning to Program in Ruby class.
update, October 2012 - An example [here] from yesterday's Python course