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.
1# Take n2n = int(input("Enter n: "))34# Calculate alternating sum5total = 06for i in range(1, n + 1):7 if i % 2 == 1:8 total += i9 else:10 total -= i1112print(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
Visit one through n.
- 2
Add odd i and subtract even i.
- 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.
๐Related Content
- ๐
Phase 6 - Learn Concepts
Review Phase 6 concepts and explanations
- ๐
Phase 6 - Quiz
Test your Phase 6 understanding with quiz questions
- ๐ป
Phase 6 - All Practice Problems
Explore all practice problems for Phase 6
- ๐
Master Your Logic Building - Complete Course
Browse all phases and tutorials
- ๐ง
Logic Building Overview
Learn about the complete logic building curriculum