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.
Answer and explanation
Concise answer
total <- 0 count <- 1 WHILE count <= n total <- total + count count <- count + 1 END WHILE OUTPUT total
Why this is correct
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.
Use the concise answer above for a quick check, then reveal the full model answer and detailed explanation.
Common mistake
No common mistake is linked to this question yet.
