Learning outcomes
By the end of this lecture, you should be able to:- sum first
nnumbers usingfor - verify result using formula
n(n+1)/2 - write variants (even/odd sums)
Basic solution
Dry run for n = 4
total = 0- add 1 -> 1
- add 2 -> 3
- add 3 -> 6
- add 4 -> 10
Formula cross-check
sum = n * (n + 1) // 2
Use formula for quick verification in exam output questions.
Variant 1: sum of even numbers up to n
Variant 2: sum of odd numbers up to n
Exam hints and traps
- inclusive range needs
n + 1 range(n)starts from0, not1- for large
n, formula is faster than loop
Practice
- Write loop sum for first
nnatural numbers. - Modify to sum from
atobinclusive. - Predict output for
n=0.
Answers
0
