Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

Sum Series with Steps Recursively

Sum a descending stepped series recursively. Students trace a nonpositive stopping condition and see why the step must move the argument toward that condition.

AdvancedPhase 3 - Level 3: Pattern RecursionExample 9 of 10
sum-series-with-steps-recursively.py
1def sum_series(n, step=1):
2 # Base case
3 if n <= 0:
4 return 0
5
6 # Recursive case
7 return n + sum_series(n - step, step)
8
9# Test
10n = int(input("Enter n: "))
11step = int(input("Enter step: "))
12result = sum_series(n, step)
13print(f"Sum: {result}")

Output

Enter n: 10
Enter step: 2
Sum: 30

In this one

  • Subtract a positive step
  • Use a nonpositive base case
  • Detect missing progress

How it works

  1. 1

    Return zero when n is nonpositive.

  2. 2

    Request the series beginning at n - step.

  3. 3

    Add the current n to the returned total.

Edge cases

What if n is already negative?

What if n is already negative?

The base case returns zero immediately.

What if step is zero?

What if step is zero?

For positive n, calls repeat until RecursionError.

What's going on

The current n is added to a smaller problem with n - step. The base case returns zero when n is nonpositive.

With n equal to seven and step two, terms are seven, five, three, and one. A positive step guarantees progress. A zero step repeats the same argument; a negative step increases it. Both can exhaust Python's call stack instead of finishing.

What if n is already negative? The base case returns zero immediately.

What if step is zero? For positive n, calls repeat until RecursionError.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

Which step is valid for progress?

Pick an answer to check it.

Question 2

What if n is already negative?

Pick an answer to check it.

Questions people ask

What if n is already negative?

The base case returns zero immediately.

What if step is zero?

For positive n, calls repeat until RecursionError.

Which step is valid for progress?

A positive step.