Code Explanation:
Define a Recursive Function:
def recursive_sum(n):
A function named recursive_sum is defined.
This function takes a single parameter n, which represents the number up to which the sum is calculated.
Base Case:
if n == 0:
return 0
This is the base case of the recursion.
If n is 0, the function stops recursing and returns 0.
The base case is essential to prevent infinite recursion.
Recursive Case:
return n + recursive_sum(n - 1)
If n is not 0, the function returns n added to the result of recursive_sum(n - 1).
This means the function calls itself with the argument n - 1 and continues reducing n until the base case is reached.
Print the Result:
print(recursive_sum(5))
The function is called with n = 5.
The function recursively calculates the sum of numbers from 5 to 1.
Recursive Flow:
When recursive_sum(5) is called:
5 + recursive_sum(4)
4 + recursive_sum(3)
3 + recursive_sum(2)
2 + recursive_sum(1)
1 + recursive_sum(0)
Base case reached, returns 0.
Returns 1 + 0 = 1.
Returns 2 + 1 = 3.
Returns 3 + 3 = 6.
Returns 4 + 6 = 10.
Returns 5 + 10 = 15.
Final Output:
15
0 Comments:
Post a Comment