# Summing a Bunch of Numbers in Pascal

Recall that we first wrote an algorithm to sum up a bunch of numbers (we get the numbers one at a time) and print the sum. Our algorithm assumes there is at least one number; here it is:
1. set sum to 0.
4. if there is another number, go to step 2.
5. print out sum.

Here is the program we wrote that implements the algorithm. Remember that we had to decide how the program knows whether there is another number or not. We chose to say that the user enters a number of 0 when there are no more numbers. THIS IS DIFFERENT THAN WHAT YOU DO IN YOUR HOMEWORK ASSIGNMENT, since in that case, the user enters how many numbers there will be.

```program calcsum;

{
This program calculates the sum of numbers
entered by the user.  It knows that there
are no more numbers to be summed when the
user enters 0.
}

var
sum : integer;  { used to accumulate the sum }
n : integer;    { holds each number in turn }

begin
sum := 0;  { Give the sum its initial value }

{ We must read at least one number }
write('Enter a number: ');

while n <> 0 do
begin
sum := sum + n;  { add the number to the sum }
{ We must read another number }
write('Enter a number: ');
end;

writeln('The sum is ', sum);
end.
```

Below we show a compilation and run of the program.

```% pc calcsum.p

% a.out
Enter a number: 13
Enter a number: 40
Enter a number: 5
Enter a number: 22
Enter a number: 16
Enter a number: 0
The sum is         96
```

CS101 - Summing a Bunch of Numbers in Pascal / Robert I. Pitts / rip@cs.bu.edu