In Java, the quotient is the result of integer division, and the remainder is what is left after the division.
Example:
7 / 2 = 3 quotient, 7 % 2 = 1 remainder
Approach:
- Divide the dividend by the divisor using the / operator to get the quotient.
- Use the % operator to get the remainder.
Expressions used in the program:
quotient = dividend/divisor;
remainder = dividend % divisor;
Note: The program will throw an ArithmeticException: / by zero when divided by 0.
Example 1: This program demonstrates how to find the quotient and remainder of two integers in Java.
public class QuotientAndRemainder {
public static void main(String[] args) {
int dividend = 556, divisor = 9;
int quotient = dividend / divisor;
int remainder = dividend % divisor;
System.out.println("The Quotient is = " + quotient);
System.out.println("The Remainder is = " + remainder);
}
}
Output
The Quotient is = 61 The Remainder is = 7
Explanation:
- dividend / divisor computes the quotient : 556 / 9 = 61.
- dividend % divisor computes the remainder : 556 % 9 = 7.
- System.out.println is used to display the results.
- Time Complexity: O(1) and Auxiliary Space: O(1)
Example 2: This program calculates the quotient and remainder for a negative dividend in Java.
public class QuotientAndRemainder {
public static void main(String[] args) {
int dividend = -756, divisor = 8;
int quotient = dividend / divisor;
int remainder = dividend % divisor;
System.out.println("The Quotient is = " + quotient);
System.out.println("The Remainder is = " + remainder);
}
}
Explanation:
- dividend / divisor computes the quotient : -756 / 8 = -94.
- dividend % divisor computes the remainder : -756 % 8 = -4.
- System.out.println is used to display the results.
- Time Complexity: O(1) and Auxiliary Space: O(1)
Example 3: This program demonstrates that division by zero in Java throws an exception.
public class QuotientAndRemainder {
public static void main(String[] args) {
int dividend = 56, divisor = 0;
int quotient = dividend / divisor;
int remainder = dividend % divisor;
System.out.println("The Quotient is = " + quotient);
System.out.println("The Remainder is = " + remainder);
}
}
Output:
Exception in thread "main" java.lang.ArithmeticException: / by zero
at QuotientAndRemainder.main(QuotientAndRemainder.java:7)
Explanation:
- dividend / divisor and dividend % divisor are invalid when divisor = 0.
- Executing the program throws ArithmeticException: / by zero.
- Java does not allow division or modulo by zero, and the program will terminate abnormally.