A function call itself for many times and return a result. [3] a) What...
Recursive Function
A function that calls itself during its execution is called a recursive function. It is a powerful programming technique that allows a function to solve complex problems by breaking them down into simpler subproblems.
Definition of a Recursive Function to find the Sum of Natural Numbers
Here is a function's definition in Python to find the sum of natural numbers from 1 to N:
```python
def calculate_sum(n):
if n == 1:
return 1
else:
return n + calculate_sum(n-1)
```
Explanation
Let's understand how the above recursive function works step by step:
1. The function is defined as `calculate_sum(n)`, where `n` represents the upper limit of the natural numbers to be summed.
2. The base case is checked using the condition `if n == 1`. If `n` is equal to 1, it means we have reached the lowest possible value in the sequence of natural numbers, so the function returns 1.
3. If the base case is not met, the function proceeds to the `else` block.
4. In the `else` block, the function recursively calls itself with the argument `n-1`. This means the function will be called again but with a smaller value of `n`.
5. The result of the recursive call is then added to `n` and returned. This step is crucial as it allows the function to build up the sum of all the natural numbers from 1 to `n`.
6. The function continues to call itself recursively, reducing the value of `n` by 1 each time, until the base case is met.
7. Once the base case is met, the function starts returning the intermediate results, and the final result is obtained as the sum of all the intermediate results.
Example Usage
Let's say we want to find the sum of natural numbers from 1 to 5 using the above recursive function.
```python
result = calculate_sum(5)
print(result)
```
The output will be:
```
15
```
Here, the function `calculate_sum(5)` is called. Since 5 is not equal to 1, the function recursively calls itself with `n-1` (i.e., `calculate_sum(4)`). This process continues until the base case is met, and the result is calculated as 15.
Benefits of Using Recursive Functions
- Recursive functions provide an elegant and concise way to solve complex problems.
- They allow us to break down a problem into smaller, more manageable subproblems.
- They make the code more readable and easier to understand.
- Recursive functions can be used to solve problems that have a natural recursive structure, such as tree traversals, factorial calculations, and searching algorithms.
To make sure you are not studying endlessly, EduRev has designed JEE study material, with Structured Courses, Videos, & Test Series. Plus get personalized analysis, doubt solving and improvement plans to achieve a great score in JEE.