Welcome to the Grade Calculator tutorial! This program calculates and displays the grade based on input scores.
Introduction
In this tutorial, we will be writing a simple C program to calculate grades based on user input scores. The program will take the score as input and determine the grade based on predefined criteria. Grading systems are widely used in educational institutions, and this simple calculator will help automate the grading process.
Objective
The objective of this program is to take the student’s score as input and display the corresponding grade. The grading scale is typically as follows:
- A: 90 – 100
- B: 80 – 89
- C: 70 – 79
- D: 60 – 69
- F: 0 – 59
The program will allow students or educators to quickly determine the grade based on the score entered.
Program Code
#include int main() { int score; char grade; // Get user input printf("Enter the score (0-100): "); scanf("%d", &score); // Validate score input if (score < 0 || score > 100) { printf("Invalid score. Please enter a score between 0 and 100.\n"); return 1; } // Determine grade based on score if (score >= 90) { grade = 'A'; } else if (score >= 80) { grade = 'B'; } else if (score >= 70) { grade = 'C'; } else if (score >= 60) { grade = 'D'; } else { grade = 'F'; } // Display grade printf("Your grade is: %c\n", grade); return 0; }
Explanation of the Program
The program starts by including the standard input/output library stdio.h
, which is essential for taking input and displaying output. It defines two variables: an integer score
to store the user’s score, and a character grade
to store the grade corresponding to the score.
After initializing these variables, the program asks the user to enter a score between 0 and 100. It uses scanf()
to take the score input. The program checks if the input is valid, i.e., between 0 and 100. If the score is invalid, it displays an error message and exits.
The program then uses a series of if-else
statements to determine the grade based on the input score. The grading criteria are as follows:
- A for scores 90 and above
- B for scores between 80 and 89
- C for scores between 70 and 79
- D for scores between 60 and 69
- F for scores below 60
Finally, the program outputs the grade using printf()
.
How to Run the Program
Follow these steps to run the program:
- Open a text editor (like Notepad, VS Code, or Sublime Text) and copy the program code into a new file.
- Save the file with a
.c
extension, for example,grade_calculator.c
. - Open a terminal (Command Prompt for Windows or Terminal for Mac/Linux) and navigate to the folder where you saved the file.
- Compile the program using a C compiler like GCC. In the terminal, run the following command:
gcc grade_calculator.c -o grade_calculator
- After successful compilation, run the program by typing:
./grade_calculator
(on Linux/Mac) or
grade_calculator.exe
(on Windows).
- Enter the score when prompted, and the program will display the corresponding grade.