In this tutorial, we will write a java program to calculate the grade of the student. Before that, you should have knowledge on the following topic in java:
Java Program to calculate and display Student Grades: The program simply takes a user input for the number of subjects and then for the marks obtained on each of those subjects.
Then the sum of the marks is calculated and then the average of that sum is calculated. The average is calculated by dividing the sum of the marks by the number of subjects. Lastly, using the if-else ladder the grade is displayed on the screen.
The grade is printed by following grade slab:
- If marks > 80, Grade is A
- If marks > 60 and <= 79, Grade is B
- If marks > 40 and <= 59, Grade is C
- Else Grade is D
You can change the grades according to your need and your question. We will perform two different programs:
- Using if else ladder
- Using Switch Case
Java program to find grade of a student using if else ladder
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | import java.util.Scanner; public class Main { public static void main(String args[]) { int marks[] = new int[5]; int i, subjects; float sum = 0, avg; Scanner sc = new Scanner(System.in); System.out.print("Enter the number of subjects: "); subjects = sc.nextInt(); System.out.println("Enter Marks for " + subjects + " Subjects: "); for (i = 0; i < subjects; i++) { marks[i] = sc.nextInt(); sum = sum + marks[i]; } avg = sum / subjects; System.out.print("Your Grade: "); if (avg > 80) { System.out.print("A"); } else if (avg > 60 && avg <= 79) { System.out.print("B"); } else if (avg > 40 && avg <= 59) { System.out.print("C"); } else { System.out.print("D"); } } } |
Output:
Enter the number of subjects: 5
Enter Marks for 5 Subjects:
55
84
72
67
90
Your Grade: B
Java Program to find grade of a student using switch case
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | import java.util.Scanner; public class Main { public static void main(String[] args) { int subjects, i; float sum = 0, percent; Scanner sc = new Scanner(System.in); System.out.println("Enter the Number of Subjects: "); subjects = sc.nextInt(); System.out.println("Enter Marks for " + subjects + " Subjects:"); for (i = 0; i < subjects; i++) { sum += sc.nextInt(); } percent = (sum / (subjects *100)) *100; System.out.println("Percentage Obtained: " + percent); switch ((int) percent / 10) { case 9: System.out.println("Your Grade: A+"); break; case 8: System.out.println("Your Grade: A"); break; case 7: System.out.println("Your Grade: B"); break; case 6: System.out.println("Your Grade: B+"); break; case 5: System.out.println("Your Grade: C"); break; default: System.out.println("Your Grade: D"); break; } } } |
Enter the Number of Subjects:
4
Enter Marks for 4 Subjects:
84
79
92
85
Percentage Obtained: 85.0
Your Grade: A