In this article we are going to see how we can subtract two numbers using recursion by Java programming language.
Java Program to Subtract Two Numbers Using Recursion
- Java Program to Subtract Two Numbers Using Recursion By Using Static Input Value
- Java Program to Subtract Two Numbers Using Recursion By Using User Input Value
Method-1: Java Program to Subtract Two Numbers Using Recursion By Using Static Input Value
Approach:
- Store two numbers in two variables.
- Call the user defined method
sub( )to find the difference and store it. The methodsub()decrements both the numbers by 1 using recursion until the smaller one reaches 0. Then it returns the other number. - Print the result.
Program:
import java.util.*;
// Main class
public class Main
{
// Recursive method to subtract two numbers
public static int sub(int num1, int num2)
{
// Returns the difference when num2 reaches zero
if(num2==0)
return num1;
else
// calls the function by decrementing both numbers by 1
return sub((num1-1),(num2-1));
}
public static void main(String[] args)
{
int num1 = 29, num2 = 15;
// Call the method and store the result
int dif = sub(num1,num2);
// Print the result
System.out.println("The difference between "+num1+" and "+num2+" is "+dif);
}
}
Output: The difference between 29 and 15 is 14
Method-2: Java Program to Subtract Two Numbers Using Recursion By Using User Input Value
Approach:
- Ask the user to enter two numbers in order.
- Store two numbers in two variables.
- Call the user defined method
sub( )to find the difference and store it. The methodsub()decrements both the numbers by 1 using recursion until the smaller one reaches 0. Then it returns the other number. - Print the result.
Program:
import java.util.*;
// Main class
public class Main
{
// Recursive method to subtract two numbers
public static int sub(int num1, int num2)
{
// Returns the difference when num2 reaches zero
if(num2==0)
return num1;
else
// calls the function by decrementing both numbers by 1
return sub((num1-1),(num2-1));
}
public static void main(String[] args)
{
// Taking user input
Scanner sc = new Scanner(System.in);
// Ask the user to enter two numbers
System.out.print("Enter two numbers to subtract ");
int num1 = sc.nextInt(), num2 = sc.nextInt();
// Call the method and store the result
int dif = sub(num1,num2);
// Print the result
System.out.println("The difference between "+num1+" and "+num2+" is "+dif);
}
}
Output: Enter two numbers to subtract 10 5 The difference between 10 and 5 is 5
Interested in programming and want to excel in it by choosing the short ways. Then, practicing with the available Java Program list is mandatory.