how do i create a java method that takes two ints and divides first int in the parameter by the second int using recursion and nno division or multiplication
Hello, I have created the method with the comments where it is required. I have made main method to test our divide method. so it takes two parameters and it is recursive, where I have not use any kind of mulitplication or division.Also output is there also. please go through it and if you have any doubt, comment down. otherwise give me upvote.
Thank you and enjoy your code.
import java.util.Scanner;
import java.lang.*;
public class Division {
// For testinng the method
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
System.out.println("Enter two numbers seperated by space:");
int a = scnr.nextInt();
int b = scnr.nextInt();
// If any number is negative, then ans is also negative.
int sign = 1;
if(a*b < 0){
sign = -1;
}
// so at last we are calculating the division is multiplied by
sign.
int ans = sign * divide(Math.abs(a),Math.abs(b));
System.out.println("Division is: "+ ans);
}
public static int divide(int a, int b){
if (a<b){
System.out.println("Reminder is: "+ a);
return 0;
}
// till a<b, this will execute.
// so every time divident is decreased by dividor and answer is
increament by 1 every time
// and when divident will be less then divider, It will terminate
with return 0 as mentioned above.
return 1 + divide(a-b,b);
}
}
// Output:
THank you. Hope you liked my answer.
Get Answers For Free
Most questions answered within 1 hours.