Alternating Sum

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

Logic BuildingIntermediate
Logic Building
# Take n
n = int(input("Enter n: "))

# Calculate alternating sum
total = 0
for i in range(1, n + 1):
    if i % 2 == 1:
        total += i
    else:
        total -= i

print(f"Alternating sum: {total}")

Output

Enter n: 5
Alternating sum: 3

Add odd numbers, subtract even numbers.

Key Concepts:

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