Recursive function


What  is recursive function ?

A recursive function is the function that calls itself during execution of program. Every recursive solution has two major cases, which are fallows:

Base case, in which the problem is simple enough to solve directly without making any further calls to the same function.

Recursive case, in which first the problem at hand divided into simpler sub-part. Second, the function calls itself but sub-parts of the problem obtained in the first stem. Third, the result is obtained by combining the solutions of simpler sub- part.
Thus we see that recursion utilized divide and conquer technique of problem solving. Divide and conquer technique is a method of solving a given problem by dividing it into two or more smaller instances.


Now for understand the recursive function let us see an example of calculating factorial of a number.

The factorial of a number id n!= n x (n-1)!

Now ,

5!= 5 x 4 x 3 x 2 x1

    =120

This can be written as:

5!= 5 x  4!
4!= 4 x 3!
3!= 3 X 2!
2!= 2 x 1!

So, finally 5! Can be written as

5!= 5 x 4 x 3 x 2 x 1!

Base case of recursive is when n=1 the result is known to be  1 as 1!=1

Recursive case of the factorial function will call itself but with a smaller value of n. so this may be.

factorial= n x factorial(n-1)

1.Write a program in python to calculate n number of factorial

def fact(n):
    if(n==1 or n==0):
        return 1
    else:
        return n* fact(n-1)
# take input from user
n=int (input("Enter the value of n :"))
print ("factorial :", fact(n))

OutPut:



2.Write a program in python to print Fibonacci series

def  fibonacci_series (n):
    if (n<2):
        return 1
    return (fibonacci_series(n-1)+ fibonacci_series(n-2))

#input number of terms
n=int (input ("Enter number of terms :"))
print("fibonacci_series")
for i in range(n):
    print(fibonacci_series(i),end="\t")


OutPut:



Thank you.

👇👇👇👇👇

What is Function ?




Comments

Popular posts from this blog

python pattern programming

Decision making statement in python

javaScript Calculator.