xxxxxxxxxx
void A(n){
if(n>1) // Anchor condition
{
return A(n-1);
}
}
xxxxxxxxxx
# Reccursion in python
def recursive_method(n):
if n == 1:
return 1
else:
return n * recursive_method(n-1)
# 5 * factorial_recursive(4)
# 5 * 4 * factorial_recursive(3)
# 5 * 4 * 3 * factorial_recursive(2)
# 5 * 4 * 3 * 2 * factorial_recursive(1)
# 5 * 4 * 3 * 2 * 1 = 120
num = int(input('enter num '))
print(recursive_method(num))
xxxxxxxxxx
The algorithmic steps for implementing recursion in a function are as follows:
Step1 - Define a base case: Identify the simplest case for which the solution is known or trivial. This is the stopping condition for the recursion, as it prevents the function from infinitely calling itself.
Step2 - Define a recursive case: Define the problem in terms of smaller subproblems. Break the problem down into smaller versions of itself, and call the function recursively to solve each subproblem.
Step3 - Ensure the recursion terminates: Make sure that the recursive function eventually reaches the base case, and does not enter an infinite loop.
step4 - Combine the solutions: Combine the solutions of the subproblems to solve the original problem.
xxxxxxxxxx
def fibonacci(n):
if n <= 1:
return n
else:
return fibonacci(n - 1) + fibonacci(n - 2)
result = fibonacci(6) # Find the 6th Fibonacci number
print(result) # Output: 8
xxxxxxxxxx
def factorial(x):
"""This is a recursive function
to find the factorial of an integer"""
if x == 1:
return 1
else:
return (x * factorial(x-1))
num = 1
print("The factorial of", num, "is", factorial(num))
xxxxxxxxxx
# Recursive function factorial_recursion()
def factorial_recursion(n):
if n == 1:
return n
else:
return n*factorial_recursion(n-1)
xxxxxxxxxx
def func(n):
if n == 1:
print(1, end=' ')
else:
func(n-1)
print(n, end=' ')
n=int(input('To what number to print? '))
func(n)
xxxxxxxxxx
def yourFunction(arg):
#you can't just recurse over and over,
#you have to have an ending condition
if arg == 0:
yourFunction(arg - 1)
return arg
xxxxxxxxxx
pythonCopydef fact(n):
"""Recursive function to find factorial"""
if n == 1:
return 1
else:
return (n * fact(n - 1))
a = 6
print("Factorial of", a, "=", fact(a))