Skip to main content

ProwessApps

Learn · Practice · Excel

Java Program to ask user to enter marks of 5 subjects and calculate the percentage then print GRADE according to marks in percentage.

Java Code Example — Conditional Programs

ADVERTISEMENT

Java Program to ask user to enter marks of 5 subjects and calculate the percentage then print GRADE according to marks in percentage.

Objective

Write a Java program to calculate the percentage of marks obtained in 5 subjects and determine the corresponding grade.

Algorithm / Approach

  1. Prompt the user to enter the marks for 5 different subjects.
  2. Add all the marks together and divide by 5.0 to calculate the percentage.
  3. Use an if-else if ladder to evaluate the percentage.
  4. Assign Grade A for ≥ 80, B for ≥ 70, C for ≥ 60, D for ≥ 50, and E for anything lower.
  5. Print the percentage and the final grade.
Test.java
import java.util.Scanner;
class Test {
 public static void main(String[] a)
 {
  Scanner s=new Scanner(System.in);
  System.out.print("Enter Marks1: ");
  int m1 = s.nextInt();
  System.out.print("Enter Marks2: ");
  int m2 = s.nextInt();
  System.out.print("Enter Marks3: ");
  int m3 = s.nextInt();
  System.out.print("Enter Marks4: ");
  int m4 = s.nextInt();
  System.out.print("Enter Marks5: ");
  int m5 = s.nextInt();
  double per =(m1+m2+m3+m4+m5)/5.0;
  System.out.println("Percentage = "+per);
  if(per>=80){
   System.out.print("Grade is A");
  }
  else if(per>=70) {
   System.out.print("Grade is B");
  }
  else if(per>=60) {
   System.out.print("Grade is C");
  }
  else if(per>=50) {
   System.out.print("Grade is D");
  }
  else {
  System.out.print("Grade is E");
  }
 }
}

Expected Output

Enter Marks1: 67
Enter Marks2: 78
Enter Marks3: 98
Enter Marks4: 67
Enter Marks5: 78
Percentage = 77.6
Grade is B

Explanation of the Program

  • The division uses 5.0 (a double) to prevent integer truncation and retain the decimal value of the percentage.
  • The program checks conditions from the highest bound downwards.
  • If the percentage is 75, the first condition (≥ 80) fails, but the second (≥ 70) passes, successfully assigning Grade B.

Complexity

Time Complexity O(1)
Space Complexity O(1)

Common Mistakes

  • Checking conditions from lowest to highest using greater-than bounds, which causes logic errors (e.g., checking ≥ 50 first would make an 85% student get a D).
  • Dividing by 5 (an integer) instead of 5.0, leading to loss of precision.
ADVERTISEMENT