Java Exercises: Divide the two specified integers using subtraction operator

Java Basic: Exercise-164 with Solution

Write a Java program to divide the two given integers using subtraction operator.

Pictorial Presentation:

Java Basic Exercises: Divide the two specified integers using subtraction operator.

Sample Solution:

Java Code:

import java.util.Scanner;
public class Solution {	
	public static float divide_using_subtraction(int dividend, int divider) {
	if (divider == 0) {
       return 0;
    float result = 0;
    while (dividend > divider) {
      dividend -= divider;
    float decimalPart = (float) dividend / (float) divider;
    result += decimalPart;
    return result;
    public static void main(String[] args) {
 Scanner in = new Scanner(System.in);
        System.out.print("Input the dividend: ");
        int dividend = in.nextInt();
		System.out.print("Input the divider: ");
        int divider = in.nextInt();
		System.out.println("\nResult: " + divide_using_subtraction(dividend,divider));		

Sample Output:

Input the dividend:  625
Input the divider:  25

Result: 25.0


Flowchart: Java exercises: Divide the two specified integers using subtraction operator.

Java Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a Java program that will accept an interger and convert it into a binary representation. Now count the number of bits which is equal to zero of the said binary represntation.
Next: Write a Java program to move every positive number to the right and every negative number to the left of a given array of integers.

What is the difficulty level of this exercise?

Java: Tips of the Day

Array vs ArrayLists:

The main difference between these two is that an Array is of fixed size so once you have created an Array you cannot change it but the ArrayList is not of fixed size. You can create instances of ArrayLists without specifying its size. So if you create such instances of an ArrayList without specifying its size Java will create an instance of an ArrayList of default size.

Once an ArrayList is full it re-sizes itself. In fact, an ArrayList is internally supported by an array. So when an ArrayList is resized it will slow down its performance a bit as the contents of the old Array must be copied to a new Array.

At the same time, it's compulsory to specify the size of an Array directly or indirectly while creating it. And also Arrays can store both primitives and objects while ArrayLists only can store objects.

Ref: https://bit.ly/3o8L2KH