Step 3 of 7
Accumulating a total
A pattern you'll use constantly: accumulating a result across a loop. Create a variable before the loop, update it on every pass, and use it after the loop.
- For a sum, start at 0 and add each value.
- For a count, start at 0 and add 1 when something matches.
- For a maximum, start with a value that anything will beat (or with the first value), and replace it whenever you see something bigger.
#include <stdio.h>
int main(void) {
int n;
scanf("%d", &n);
int total = 0;
int passed = 0;
for (int i = 0; i < n; i++) {
int grade;
scanf("%d", &grade);
total += grade;
if (grade >= 50) {
passed++;
}
}
printf("average %d, passed %d\n", total / n, passed);
return 0;
}
5
72 45 90 38 60
average 61, passed 3
Reading a list
A common input format is "first the count, then that many values". Read the count first, then loop that many times, reading one value per pass. Each scanf continues from where the last one stopped, so the values can be on one line or many.
Where to declare things
total and passed are declared before the loop, because they must survive across passes and be used afterwards. grade is declared inside, because each pass only needs its own current value. If total were declared inside the loop, it would be reset to 0 every pass.
For a maximum, starting at 0 works only when all values are at least 0. For values that might be negative, start with the first value instead.
Your turn: the first number of input is n, followed by n damage values. Print the total damage and the highest single hit:
Input:
4
27 100 64 9
Output:
total 200
max 100