Recursion is a way of programming or coding a problem, in which a function calls itself one or more times in its body. Usually, it is returning the return value of this function call. If a function definition fulfils the condition of recursion, we call this function a recursive function.
Remember, the termination condition:
- A recursive function has to terminate to be used in a program.
- A base case is a case, where the problem can be solved without further recursion. Tips: start by identifying the base case.
- A recursive function terminates, if with every recursive call the solution of the problem is downsized and moves towards a base case.
Let us solve the following exercises, following this approach:
- Write the pseudocode of the solving this exercise using a recursive approach
- Implement the pseudocode in a Python program
Exercise 1
Write a recursive function that accepts two numbers as its argument and returns its power.
Exercise 2
Write a recursive function that calculate sum of first n natural numbers.
Exercise 3
Write a program that reads two integers from keyboard and calculate the greatest common divisor (gcd) using recursive function
Exercise 4
Exercise on Rosalind on RNA.
Sum of Digits of an Integer Using Recursion
Write a Python program to get the sum of the digits of a non-negative integer using recursion.