Display Student Grade Based on Average Mark - C Program

Display Student Grade Based on Average Mark - C Program

Display Student Grade Based on Average Mark - C Program

This blog post demonstrates a simple C program that calculates a student's average mark and determines their grade based on that average. The program handles all logic within the main function, making it straightforward and easy to follow.

Program Code

#include <stdio.h>

int main() {
    int numSubjects;
    float sum = 0.0, average;
    
    // Prompt user for number of subjects
    printf("Enter the number of subjects: ");
    scanf("%d", &numSubjects);

    // Validate the number of subjects
    if (numSubjects <= 0) {
        printf("Number of subjects must be greater than 0.\n");
        return 1;
    }

    // Input marks for each subject
    for (int i = 0; i < numSubjects; i++) {
        float mark;
        printf("Enter mark for subject %d: ", i + 1);
        scanf("%f", &mark);
        sum += mark;
    }

    // Calculate average mark
    average = sum / numSubjects;

    // Determine and display grade
    if (average >= 90) {
        printf("The average mark is %.2f\n", average);
        printf("The grade is A\n");
    } else if (average >= 80) {
        printf("The average mark is %.2f\n", average);
        printf("The grade is B\n");
    } else if (average >= 70) {
        printf("The average mark is %.2f\n", average);
        printf("The grade is C\n");
    } else if (average >= 60) {
        printf("The average mark is %.2f\n", average);
        printf("The grade is D\n");
    } else {
        printf("The average mark is %.2f\n", average);
        printf("The grade is F\n");
    }

    return 0;
}

Explanation

This program performs the following steps:

  1. Include the Standard I/O Library: The program includes <stdio.h> for input and output functions.
  2. Read Number of Subjects: The program prompts the user to enter the number of subjects and validates the input to ensure it is greater than 0.
  3. Input Marks: It collects marks for each subject and computes the total sum of these marks.
  4. Calculate Average: The average mark is calculated by dividing the total sum by the number of subjects.
  5. Determine and Display Grade: The program determines the letter grade based on the average mark and prints the average and grade.

This program provides a clear example of using conditional statements and arithmetic operations in C programming.

Comments

Popular Posts