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

Alternating Series Sum

Sum alternating reciprocal terms with conditions. Students trace odd-position addition, even-position subtraction, and a four-decimal display of the result.

IntermediatePhase 2 - Level 3: Mathematical & Logical PatternsExample 13 of 13
alternating-series-sum.py
1# Take n
2n = int(input("Enter n: "))
3
4# Calculate sum
5sum_alt = 0
6for i in range(1, n + 1):
7 if i % 2 == 1:
8 sum_alt += 1 / i
9 else:
10 sum_alt -= 1 / i
11
12print(f"Sum: {sum_alt:.4f}")

Output

Enter n: 5
Sum: 0.7833

In this one

  • Alternate fraction signs
  • Test denominator parity
  • Separate formatting from storage

How it works

  1. 1

    Visit denominators one through n.

  2. 2

    Add odd reciprocals and subtract even reciprocals.

  3. 3

    Display the final total to four decimal places.

Edge cases

Which sign does the third term use?

Which sign does the third term use?

Plus, because three is odd.

What happens for n <= 0?

What happens for n <= 0?

The loop is empty and the total stays zero.

What's going on

The first reciprocal is added, the second subtracted, and the pattern repeats. The parity test uses the denominator i to choose the sign.

For two terms the result is 1 - 1/2 = 0.5. Each term uses / so fractions remain nonzero. The final .4f formats the total for display; it does not make the underlying arithmetic exact.

Which sign does the third term use? Plus, because three is odd.

What happens for n <= 0? The loop is empty and the total stays zero.

Quiz

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

Question 1

How is the second term handled?

Pick an answer to check it.

Question 2

Which sign does the third term use?

Pick an answer to check it.

Questions people ask

Which sign does the third term use?

Plus, because three is odd.

What happens for n <= 0?

The loop is empty and the total stays zero.

How is the second term handled?

Subtract 1 / 2.