Exam-style question
Try this first
Write pseudocode for an algorithm that accepts a positive integer n and outputs the sum of all integers from 1 to n. Your algorithm must use assignment and iteration. Explain why your algorithm is correct and why it terminates.
Model answer
What a good answer should say
- total <- 0 count <- 1 WHILE count <= n total <- total + count count <- count + 1 END WHILE OUTPUT total The algorithm is correct because total starts at zero and each integer from 1 through n is added once.
- The value of count increases by one after each iteration, so the loop reaches n and then stops.
- Since n is a positive integer and count increases on every iteration, the algorithm terminates.
Explanation
Why this works
The initial assignments set up the running total and the first integer. The loop adds the current count and then advances it.
The condition ensures that every value from 1 to n is included exactly once. The increasing count provides a logical reason that the loop will terminate.
Common mistake
No common mistake is linked to this question yet.
