Time to bring everything you've learned together in one small project. This project stores 3 student scores and works out the total, average, and pass/fail result. It's a chance to practice variables, arrays, loops, functions, and if...else all in one place.
c
#include <stdio.h>
float calculateAverage(int scores[], int size) {
int total = 0;
for (int i = 0; i < size; i++) {
total += scores[i];
}
return total / (float) size;
}
int main() {
int scores[] = {75, 82, 68};
int size = 3;
float average = calculateAverage(scores, size);
printf("Average score: %.2f
", average);
if (average >= 60) {
printf("Result: Passed");
} else {
printf("Result: Try again");
}
return 0;
}calculateAverage() loops through the scores in the array, adds them up, and returns the average. In main(), that average is used to decide pass/fail with a condition.
You should see
Average score: 75.00 Result: PassedInfo
total / (float) size uses type casting so the result comes out as a decimal. Writing total / size alone does integer division, which drops the decimal part.