Sum Them Forth

Problem #326

Tags: unlabeled

Who solved this?

No translations... yet

Here comes the first exercise in Forth programming language. If you are not acquainted, please refer to this short intro, which also contains links to the online interpreter and to famous book on the language.

Problem Statement

Calculate the sum of several decimal values, given in input as a single line. Print the result. Do this in Forth.

Details

While Forth provides . (dot) word for printing out numbers, it doesn't generally have ready word for reading numbers from input. So you'll need to construct it.

Word key reads single character from input and leaves its ASCII code on stack. Reading char "2" for example will push 50 onto the stack. So it would be good to read characters inside a loop, subtract 48 (code for "0") from them, and add to previously collected result multiplied by 10.

E.g. we can define the word for reading single digit and read two-digit value:

: dig key 48 - ;
dig 10 * dig +
.

In our more general case stop reading number when space is encountered (its code is 32, anyway less than any of digits).

Input contains a sequence of decimal numbers to be summed, in a single line. It ends with zero (and newline).

Answer should give just a single value - sum of the sequence.

Example

input:
1 4 9 16 25 0

answer:
55
You need to login to get test data and submit solution.