Grade Calculator

beginner Programming Basics

Problem

Read marks (0 to 100) and print the grade: A for 90 or more, B for 80 to 89, C for 70 to 79, D for 60 to 69, F for less than 60. If the marks are less than 0 or more than 100, print Invalid marks.

Constraints

  • -1000 <= marks <= 1000

Examples

Input

85

Output

B

Solutions

Best approachTime O(1)Space O(1)

An if / else if chain stops at the first true condition. So we check invalid values first, then test the grades from high to low.

Same code works in Java810172125Basic features only, so nothing changes between versions.
/*
 * Problem : Convert marks to a grade.
 * Input   : One integer (marks).
 * Output  : A, B, C, D, F or Invalid marks.
 * Approach: Test the ranges from high to low.
 * Time    : O(1)
 * Space   : O(1)
 * Java    : 8 or newer.
 */
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        int marks = new Scanner(System.in).nextInt();

        // Step 1: Check for invalid marks first.
        if (marks < 0 || marks > 100) {
            System.out.println("Invalid marks");
        // Step 2: Test the ranges from high to low. The first true condition is used, so we do not need a lower limit.
        } else if (marks >= 90) {
            System.out.println("A");
        } else if (marks >= 80) {
            System.out.println("B");
        } else if (marks >= 70) {
            System.out.println("C");
        } else if (marks >= 60) {
            System.out.println("D");
        // Step 3: All other marks are below 60.
        } else {
            System.out.println("F");
        }
    }
}
Hints (2)
  1. Which check must come first?
  2. Why do you not need 'marks < 100' in the A test?