C program to read four subject grades, validate inputs between 0 and 10, calculate the average, and display it with two decimal precision.
#include <stdio.h>
int main() {
// Array to store the grades of the 4 subjects
float voti[4];
float somma = 0.0;
float media;
// Loop to read grades from the keyboard
for (int i = 0; i < 4; i++) {
printf("Enter the grade for subject %d (0-10): ", i + 1);
scanf("%f", &voti[i]);
// Simple check for valid values
if (voti[i] < 0 || voti[i] > 10) {
printf("Error: the grade must be between 0 and 10. Try again.\n");
i--; // decrement i to repeat the input
}
}
// Calculate the sum of the grades
for (int i = 0; i < 4; i++) {
somma += voti[i];
}
// Calculate the average
media = somma / 4;
// Print the result
printf("\nThe average grade is: %.2f\n", media);
return 0;
}C development environment (e.g. GCC, Visual Studio Code, Code::Blocks)
Keyboard input (stdin)
Console output (stdout)
No external libraries required