Lesson 3.1 · Write it
Sum until zero
A whole programPython or Java7 tests, 4 of them hidden
On a phone? Put the lines in order instead
Write a program that reads whole numbers one at a time and prints their sum when it reads 0.
- Read one number per line.
- Keep a running total, starting at
0. - Add each number to the total.
- When the number is
0, stop reading and printSum:followed by the total. - The stop value
0is not added to the total. - If the very first number is
0, the total is0.
All numbers are whole numbers. Your program is run several times. Only what it prints is checked.
Running Java here comes later. You can put this answer's lines in order instead. You can still write your Java answer (it stays while this page is open) and compare it with our worked solution. Or try this exercise in Python.
Examples
Your program is run 7 times: the 3 examples below, and 4 hidden ones that check the rules above. Only what it prints is checked.
two positive numbers then stop (rules 3 and 4)
You type
- typed: 5
- typed: 3
- typed: 0
It prints
Sum: 8
one number then stop (rule 3)
You type
- typed: 10
- typed: 0
It prints
Sum: 10
stop immediately, sum is 0 (rule 6)
You type
- typed: 0
It prints
Sum: 0