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

Alternating Sum

Evaluate one minus two plus three minus four through n in Python. Students use position parity to choose a term's sign and trace the alternating running total.

IntermediatePhase 6 - Category 4: Mathematical CombinationsExample 3 of 10
alternating-sum.py
1# Take n
2n = int(input("Enter n: "))
3
4# Calculate alternating sum
5total = 0
6for i in range(1, n + 1):
7 if i % 2 == 1:
8 total += i
9 else:
10 total -= i
11
12print(f"Alternating sum: {total}")

Output

Enter n: 5
Alternating sum: 3

In this one

  • Alternate integer signs
  • Choose by parity
  • Trace intermediate totals

How it works

  1. 1

    Visit one through n.

  2. 2

    Add odd i and subtract even i.

  3. 3

    Print total after all signs have been applied.

Edge cases

Is the first term positive?

Is the first term positive?

Yes. One is odd and enters the addition branch.

What happens for n = 0?

What happens for n = 0?

The total remains zero.

What's going on

Odd i values are added and even i values subtracted. The loop still advances upward by one; only the arithmetic update changes.

For n equal to four, totals become one, minus one, two, then minus two. This alternates whole integers, unlike the alternating reciprocal lesson. Zero or negative limits leave the accumulator at zero because no iterations occur.

Is the first term positive? Yes. One is odd and enters the addition branch.

What happens for n = 0? The total remains zero.

Quiz

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

Question 1

What is the result through four?

Pick an answer to check it.

Question 2

Is the first term positive?

Pick an answer to check it.

Questions people ask

Is the first term positive?

Yes. One is odd and enters the addition branch.

What happens for n = 0?

The total remains zero.

What is the result through four?

-2.