Loading your workspace…
Loading your workspace…
Read the marks a student scored in a number of subjects and print their average.
#include <stdio.h>
int main(void) {
int n, i, marks;
int total = 0;
double average;
printf("Enter the number of subjects:\n");
if (scanf("%d", &n) != 1 || n < 1) {
printf("Error: enter at least one subject\n");
return 1;
}
printf("Enter the marks of each subject:\n");
for (i = 1; i <= n; i++) {
if (scanf("%d", &marks) != 1) {
printf("Error: invalid marks\n");
return 1;
}
total += marks;
}
average = (double)total / n;
printf("Average marks: %.2f\n", average);
return 0;
}
Input
3
60 75 90Output
Enter the number of subjects:
Enter the marks of each subject:
Average marks: 75.00Input
2
0 0Output
Enter the number of subjects:
Enter the marks of each subject:
Average marks: 0.00The total is an int, but the average is computed as (double)total / n. The cast forces floating-point division, so an average such as 76.67 is not truncated to 76.
The running total avoids storing every mark, so the program needs only one variable for the sum.
Edit the program and press Run. It is free and needs no sign-in.
Copy a sample and paste it into the STDIN box in the editor before you press Run.
3 60 75 90
Expected output
Enter the number of subjects: Enter the marks of each subject: Average marks: 75.00
2 0 0
Expected output
Enter the number of subjects: Enter the marks of each subject: Average marks: 0.00
Without the cast, integer division would drop the fractional part of the average.
O(n): each mark is read and added once.
The total of integer marks is an integer; only the division needs floating point.
Non-numeric input, which would otherwise leave the marks variable with an old value.
Multiply each mark by its weight, sum the products and divide by the sum of the weights.
Back to all RCU 21BCA1C1P lab programs.