Open In App

Program to find Quotient And Remainder in Java

Improve
Improve
Like Article
Like
Save
Share
Report

The remainder is the integer left over after dividing one integer by another. The quotient is the quantity produced by the division of two numbers. For example,

(7/2) = 3 In the above expression 7 is divided by 2, so the quotient is 3 and the remainder is 1.

Approach:

Divide the dividend by the divisor using / operator. Both dividend and divisor can be of any type except string, the result will also be computed accordingly. Get the remainder using % operator. Expressions used in program to calculate quotient and remainder:

quotient = dividend / divisor;
remainder = dividend % divisor;

Note: The program will throw an ArithmeticException: / by zero when divided by 0. 

Explanation:

Consider Dividend = 100 and Divisor = 6 Therefore, Quotient = 100/6 = 16 Remainder = 100%6 = 4

Below are programs that illustrate the above approach: 

Program 1: 

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

Time Complexity: O(1)

Auxiliary Space: O(1)

Program 2: For a negative number. 

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);
    }
}


Output:

The Quotient is = -94
The Remainder is = -4

Time Complexity: O(1)

Auxiliary Space: O(1)

Program 3: This program will throw an ArithmeticException as the divisor = 0. 

java




// Class 
public class QuotientAndRemainder {
  
    // Main driver method 
    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)

Time Complexity: O(1)

Auxiliary Space: O(1)



Last Updated : 13 Mar, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads