Home
Time Box
Calculator
Snake
Blogs
Hacks

Question 5 • 5 min read


Question 5: If, While, Else (Unit 3-4)

Situation: You are developing a simple grading system where you need to determine if a given score is passing or failing.

Part (a)

(a) Explain the roles and usage of the if statement, while loop, and else statement in Java programming. Provide examples illustrating each.

Answer

public class Example {
    public static void main(String[] args) {
        int number = 10;

        // Example of if-else statement
        if (number > 0) {
            System.out.println("Number is positive.");
        } else if (number < 0) {
            System.out.println("Number is negative.");
        } else {
            System.out.println("Number is zero.");
        }

        // Example of a while loop
        int i = 1;
        while (i <= 5) {
            System.out.println("Counting: " + i);
            i++;
        }
        System.out.println("Loop ends.");
    }
}
Example.main(null);
Number is positive.
Counting: 1
Counting: 2
Counting: 3
Counting: 4
Counting: 5
Loop ends.

Part (b)

(b) Code:

You need to implement a method printGradeStatus that takes an integer score as input and prints “Pass” if the score is greater than or equal to 60, and “Fail” otherwise. Write the method signature and the method implementation. Include comments to explain your code.

Answer

public class GradeStatusPrinter {
    // Method to print the grade status based on the score
    public static void printGradeStatus(int score) {
        // Check if the score is greater than or equal to 60
        if (score >= 60) {
            // If score is greater than or equal to 60, print "Pass"
            System.out.println("Pass");
        } else {
            // If score is less than 60, print "Fail"
            System.out.println("Fail");
        }
    }

    public static void main(String[] args) {
        // Example usage of the method
        printGradeStatus(60); // Output: Pass
        printGradeStatus(55); // Output: Fail
    }
}
GradeStatusPrinter.main(null);
Pass
Fail