Alternating Sum

Calculate 1 - 2 + 3 - 4 + ... ± n.

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

What's going on

Add odd numbers, subtract even numbers.

Key Concepts:

Check if number is odd or even
Add if odd, subtract if even
Alternating pattern