In this article, we will learn about python program to subtract two numbers using recursion with examples.
The task is to subtract two numbers in python using recursion. For example,
If x = 10 and y = 5, then output is 10 – 5 = 5.
Method 1: Using Static Input
- Define a function that accepts parameter x and y.
- Call this function recursively with x-1 and y-1 until y becomes 0.
- Return the value of x when y is 0.
Basically we are decreasing value of x and y together by 1 until y becomes zero. In this way, we are decreasing value of x by y.
def subtract(x, y): if(y == 0): return x else: return subtract(x - 1, y - 1) a = 658 b = 640 result = subtract(a, b) print("Result:", result)
Method 2: Using User Input
In below program, we took input from user using input() method. Then, type casted into integer using int.
def subtract(x, y): if(y == 0): return x else: return subtract(x - 1, y - 1) x = int(input("Enter a number")) y = int(input("Enter another number")) result = subtract(x, y) print("Result:", result)
Enter a number 12 Enter another number 2 Result: 10
That’s how we can write python program to subtract two numbers using recursion.
Learn about more python examples at – https://tutorialwing.com/python-tutorial/