Calculating the sum and average
What you'll learn: How to use a loop to visit every element in an array to calculate a total and find the arithmetic mean.
The "Piggy Bank" Analogy
Imagine you have a row of five piggy banks. To find out the total amount of money you have, you can’t just look at the shelf and know the answer. You have to walk down the line, pick up each bank one by one, shake out the coins, and add them to a running total in your head.
Calculating the sum of an array works exactly like this. We create a "bucket" variable (the sum), start it at zero, and then use a for loop to visit every "bank" (array index) to add its contents to our bucket.
Coding the Sum
To calculate a sum, we use the += operator inside a loop. Once the loop finishes, we have our total. To find the average, we simply take that total and divide it by the number of elements in the array.
#include <stdio.h>
int main() {
int scores[] = {85, 90, 78, 92, 88};
int length = 5;
int sum = 0; // Our "running total" bucket
float average = 0.0;
// Step 1: Calculate the sum
for (int i = 0; i < length; i++) {
sum += scores[i];
}
// Step 2: Calculate the average
// We cast sum to a float to get a precise decimal result
average = (float)sum / length;
printf("Total Sum: %d\n", sum);
printf("Average: %.2f\n", average);
return 0;
}
Important Considerations
- Initialize to Zero: Always set your
sumvariable to0before starting the loop. If you don't, it might start with a random "garbage" value from your computer's memory, ruining your math. - Floating Point Precision: When calculating the average, remember that an integer divided by an integer results in an integer in C (it chops off the decimals). By using
(float)sum, we tell C to treat the math as a decimal calculation so we don't lose accuracy. - Loop Bounds: Ensure your loop stops exactly at
length - 1. If you try to add a sixth element to a five-element array, your program will crash or produce a nonsensical total.
Key takeaway
To process array data, use a for loop to accumulate values into a single variable, then perform your final calculations after the loop finishes.