C++ program to find student grades using if-else:
In this post, we will learn how to find the grades of Students using if-else checks. It will take the marks for a user as input and using a if-else block, it will print the grade.
The program will take the marks for n number of subjects. Then it will find the average from these marks and print out the grade based on it.
Below is the algorithm that the program will use:
Algorithm to find student grades:
- Take the total number of subjects from the user.
- Read marks for each of these subjects one by one.
- Find the average of all these marks.
- Using if-else, find the grade and print it out.
C++ program:
Below is the complete C++ program:
#include <iostream>
using namespace std;
int main()
{
int GRADE_A_MIN = 90;
int GRADE_B_MIN = 70;
int GRADE_C_MIN = 50;
int GRADE_D_MIN = 0;
int totalSubjects;
int totalMarks = 0;
int avgMarks;
int currentMarks;
cout << "Enter total number of subjects :" << endl;
cin >> totalSubjects;
for (int i = 0; i < totalSubjects; i++)
{
cout << "Enter marks for subject " << i + 1 << " :" << endl;
cin >> currentMarks;
totalMarks += currentMarks;
}
avgMarks = totalMarks / totalSubjects;
if (avgMarks > GRADE_A_MIN)
{
cout << "Grade A" << endl;
}
else if (avgMarks > GRADE_B_MIN)
{
cout << "Grade B" << endl;
}
else if (avgMarks > GRADE_C_MIN)
{
cout << "Grade C" << endl;
}
else
{
cout << "Grade D" << endl;
}
}
Explanation:
In this program :
- GRADE_A_MIN, GRADE_B_MIN, GRADE_C_MIN and GRADE_D_MIN are minimum values that a student needs for a specific grade. GRADE_A_MIN is the minimum marks for Grade A, GRADE_B_MIN is the minimum marks for grade B etc.
- We are reading the total subjects from the user and storing that value in totalSubjects.
- Using a for loop, we are reading the marks of the user one by one. Each mark is stored in currentMarks and that marks is added to totalMarks.
- The average marks, avgMarks is calculated by dividing the total marks by total subjects.
- Finally, we are comparing this avgMarks with the grade constants and printing the grade for that marks.
Sample Output:
Enter total number of subjects :
3
Enter marks for subject 1 :
40
Enter marks for subject 2 :
45
Enter marks for subject 3 :
56
Grade D
Enter total number of subjects :
4
Enter marks for subject 1 :
89
Enter marks for subject 2 :
90
Enter marks for subject 3 :
93
Enter marks for subject 4 :
94
Grade A
You might also like:
- C++ program to find out the sum of factorial series 1! + 2! + 3! + 4!…
- C++ program to find the sum of digits of a number
- C++ program to delete a file
- C++ program to find the sum of digits in a String
- 3 different C++ program to find the largest of three numbers
- How to convert decimal to binary in C++