Skip to content
ExamSpine

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.

  1. Read one number per line.
  2. Keep a running total, starting at 0.
  3. Add each number to the total.
  4. When the number is 0, stop reading and print Sum: followed by the total.
  5. The stop value 0 is not added to the total.
  6. If the very first number is 0, the total is 0.

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

    1. typed: 5
    2. typed: 3
    3. typed: 0

    It prints

    Sum: 8
  • one number then stop (rule 3)

    You type

    1. typed: 10
    2. typed: 0

    It prints

    Sum: 10
  • stop immediately, sum is 0 (rule 6)

    You type

    1. typed: 0

    It prints

    Sum: 0
solution.pySolution.java