Code Explanation:
def recursive_sum(n):
This defines a function named recursive_sum that takes one argument n.
The function is designed to calculate the sum of all integers from n down to 0 using recursion.
if n == 0:
This checks whether n is equal to 0.
This is the base case of the recursive function. A base case is a condition where the recursion stops. Without it, the function would call itself indefinitely, causing a stack overflow error.
return 0
If the condition n == 0 is true, the function returns 0.
This is the terminating condition of the recursion, ensuring that the function doesn't call itself further when n reaches 0.
return n + recursive_sum(n - 1)
If n is not 0, this line gets executed.
It does two things:
Adds the current value of n to the result of the function call recursive_sum(n - 1).
Calls recursive_sum with a smaller value (n - 1), which moves closer to the base case.
This is the recursive step where the function breaks the problem into smaller sub-problems.
print(recursive_sum(4))
This calls the recursive_sum function with the argument 4.
The function starts the recursive process and ultimately prints the final result after all recursive calls complete.
Step-by-Step Execution
Let’s see how the function runs when n = 4:
1st Call:
n = 4
The condition if n == 0 is false.
The function returns:
4 + recursive_sum(3)
2nd Call:
n = 3
The condition if n == 0 is false.
The function returns:
3 + recursive_sum(2)
3rd Call:
n = 2
The condition if n == 0 is false.
The function returns:
2 + recursive_sum(1)
4th Call:
n = 1
The condition if n == 0 is false.
The function returns:
1 + recursive_sum(0)
5th Call (Base Case):
n = 0
The condition if n == 0 is true.
The function returns 0.
Returning Results
Now, the results are returned step by step:
recursive_sum(0) returns 0.
recursive_sum(1) returns 1 + 0 = 1.
recursive_sum(2) returns 2 + 1 = 3.
recursive_sum(3) returns 3 + 3 = 6.
recursive_sum(4) returns 4 + 6 = 10.
Final Output:
10
0 Comments:
Post a Comment