Python Programs | IT Developer
IT Developer

Python Programs



Share with a Friend

Python Programs - Recursion Functions

Recursive function to compute sum of first N numbers - Python Program

Example 1 :

def sum_n(n): """Return sum of first n natural numbers.""" if n == 0: return 0 return n + sum_n(n-1) print(sum_n(5))

Output

 
OUTPUT  :
15

Example 2 : Advanced Program

def recursive_sum_n(n): """ Calculates the sum of the first N natural numbers recursively. Args: n (int): The number up to which the sum is calculated. Must be a non-negative integer. Returns: int: The sum of the first N natural numbers. """ if n <= 1: # Base case: if n is 0 or 1, return n return n else: # Recursive step: add n to the sum of (n-1) numbers return n + recursive_sum_n(n - 1) # Example Usage: num = int(input("Enter a number : ")) if num < 0: print("Please enter a non-negative number.") else: result = recursive_sum_n(num) print(f"The sum of the first {num} natural numbers is: {result}") num_two = 10 if num_two < 0: print("Please enter a non-negative number.") else: result_two = recursive_sum_n(num_two) print(f"The sum of the first {num_two} natural numbers is: {result_two}")

Output

 
OUTPUT  :
Enter a number  : 5
The sum of the first 5 natural numbers is: 15
The sum of the first 10 natural numbers is: 55

Explanation:

 

The recursive_sum_n(n) function calculates the sum of the first n natural numbers using recursion.

  • Base Case:

The function first checks for the base case: if n <= 1: return n. This is crucial for stopping the recursion. If n is 0, the sum is 0. If n is 1, the sum is 1. This condition prevents infinite recursion.

  • Recursive Step:

If n is greater than 1, the function executes the recursive step: return n + recursive_sum_n(n - 1). In this step, the function adds the current value of n to the result of calling itself with n-1. This effectively breaks down the problem into smaller, similar subproblems. For example, recursive_sum_n(5) becomes 5 + recursive_sum_n(4), which then becomes 5 + (4 + recursive_sum_n(3)), and so on, until the base case (recursive_sum_n(1)) is reached. The results are then accumulated back up the call stack to provide the final sum.