Sum and Average

Now that you can go through an array, let's look at what such loops are used for most often. The first pattern adds everything up. You know it from the lesson on loops; with an array, you add up its elements. Say you have the prices of the things in your shopping cart and want the total:

int prices[] = {120, 45, 300, 85};
int count = sizeof(prices) / sizeof(prices[0]);
int total = 0;
for (int i = 0; i < count; i++) {
    total += prices[i];
}
printf("Total: %d\n", total);

This prints:

Total: 550

The variable total collects the sum. It starts at 0, before the loop, because before you add anything, the sum is zero. In each iteration, total += prices[i] adds one price: after the first iteration, total is 120, then 165, 465 and finally 550. The printf comes after the loop, when the sum is complete. Inside the loop, it would print every partial sum.

The average is the sum divided by the number of values. Watch out for integer division here: total and count are both int, so total / count is 137, not 137.5, just like 7 / 2 is 3. On this site, you'll often notice it through an error message. If you print the result with %.2f, as in printf("Average: %.2f\n", total / count);, the program doesn't compile:

main.c:10:31: error: format specifies type 'double' but the argument has type 'int' [-Werror,-Wformat]

%.2f needs a decimal number, but total / count is a whole number. Under the message, Clang suggests %.2d, but that wouldn't help: the decimal part would still be lost. Instead, turn the sum into a double before dividing, with (double):

double average = (double)total / count;
printf("Average: %.2f\n", average);

This prints:

Average: 137.50

(double)total makes a decimal number from total, and a decimal number divided by a whole number gives a decimal number. Where you put (double) matters. (double)(total / count) first divides two whole numbers and only then turns 137 into 137.00: too late. The same goes for double average = total / count;. The variable is a double, but the division has already dropped the .5.

Instructions

The array points holds your points from four tests. Create a variable total with the value 0. Then go through points with a for loop and add each element to total with +=.

After the loop, print the sum as Total: 94.

At the end of the program, create a variable average of type double with the average, and print it with one decimal place: Average: 23.5. If your program prints Average: 23.0, read the part about integer division again.

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

7/12