Python Program to Add two Numbers using Recursion

In this article, we will learn about how to write python program to add two numbers using recursion.

Getting Started

As per wikipedia,
In computer science, recursion is a method of solving a computational problem where the solution depends on solutions to smaller instances of the same problem.

In programming, we call same function recursively until certain conditions are satisfied. Once specified condition are satisfied, we terminate the recursive call. Results are calculated back from last function call to first function call.

We can write python program to add two numbers using recursion as shown below –

Using + Operator

We recursively call same function until second argument is 0.

In other words, we call same function until value of second argument decreases to 0.

We can add two numbers in python using + operator and recursion as shown below –

 
def add(x, y):
    if(y == 0):
        return x
    return add(x, y - 1) + 1

print("Sum =", add(110, 21))

Output:

 
Sum = 131

Without Using + Operator

In this method, we won’t be using addition operation (i.e. + operator). Instead we will use bitwise XOR operator (^ operator) and bitwise AND operator (& operator) to get the desired result.

We derive logic to add two numbers from Half Adder Logic

We can add two numbers in python using bitwise operator and recursion as shown below –

 
def add(x, y):
    if (y == 0):
        return x
    else:
        return add( x ^ y, (x & y) << 1)
         
print("Sum =", add(15, 31))

Output:

 
Sum = 46

Learn to add two numbers without using addition operator and recursion in python.

Reference: recursion in computer science

Learn more python examples at – https://tutorialwing.com/python-tutorial/

Leave a Reply