# Sum the numbers on standard in

Consider a stream/file with one integer per line. For example:

123
5
99


Your code should output the sum of these numbers, that is 227.

The input format is strictly one integer per line. You cannot, for example, assume the input is on one line as an array of integers.

You can take input either from STDIN, in form of a filename, or a file with a name of your choice; you can choose which one. No other ways of getting input are allowed.

The input will contain at least one integer. You can assume all integers are non-negative and that their total sum is less than 232.

• Is there a trailing newline? Is that newline optional? – Please stop being evil Mar 24 '17 at 6:50
• Hi! I downvoted this challenge because it goes against our community standards for acceptable input/output formats by having a restrictive input format. – AdmBorkBork Mar 24 '17 at 15:34
• @AdmBorkBork and I discussed this at length in the chat room. We have agreed to disagree :) – user9206 Mar 24 '17 at 17:09
• As the author of the things-to-avoid of cumbersome I/O and arbitrarily overriding defaults, I want to defend this challenge on those grounds. Here, the processing input is the meat of the challenge, not extra work that distracts from the main challenge. It's not "add numbers" with weird I/O requirements, it's "do this I/O" with adding as a step. Overruling the standard I/O is necessary for answers not to shortcut across the main task. – xnor Mar 24 '17 at 18:58
• Why can't function input be used? – CalculatorFeline Apr 9 '17 at 21:02

## Lua, 59 bytes 57 bytes

New code: 57 bytes

i,s=0,0;repeat i,s=i+s,io.read("*l")until not s print(i)


We initialize i and s to 0. For each iteration, we add s to i and load in a new s from stdin. Lua has implicit string -> number coercions when doing numeric operations on a string.

Old code: 59 bytes

i=0;io.read("*a"):gsub(".-\n",function(g)i=i+g end)print(i)


Takes entire stdin and turns it into a string, gsubs over the entire string to extract lines, uses implicit number conversion and adds the lines to i, then prints i.

# Carrot, 6 bytes

#^A
+


Note the trailing space after the +.

Explanation:

#   //Set the stack to the entire input
^   //Convert to operations mode
A\n //Split the stack into an array on a new line
+   //Add all the arguments of the array together
//Implicitly output the result

• This is one of the reasons I am doing the rewrite of Carrot. With the new lexer, the space after + would not be needed as it will be understood that + takes no arguments. – Kritixi Lithos Jul 19 '17 at 13:16
• @Cowsquack Ah nice that'll be good. – TheLethalCoder Jul 19 '17 at 13:17

# Ly, 2 bytes

&+


Try it online!

A Ly builtin that would beat the accepted answer if it wasn't a 2-byte builtin...

# Triangular, 15 bytes

(\$]U]P.%p/+U(<  Try it online! Formats into this triangle:  ( \$
] U ]
P . % p
/ + U ( <


Explanation:

The IP starts from the top of the triangle, moving Southeast. So the first code that is executed is this:

($]  That simply reads integers as input until there is no more input. This is how the interpreter sees the next part: p(U+P]U%  • p pops the EOF from the stack. • ( opens a loop (to add the inputted integers). • U pulls the "memory" (register) value onto the stack if it is not zero. • + adds the top two stack values together, pops them, and pushes the result. • P pops the top of stack into memory. Now, if we've added all inputted integers together, nothing will be on the stack. • ] ends the loop if the top of the stack is falsy (or the stack is empty). • U pulls the memory value onto the stack. • % prints it. • Another loop is created at the end of the code, but that doesn't do anything as the IP runs off the playing field and terminates. # q/kdb+, 14 bytes Solution: sum"J"$(0:):f


Example:

q)system "cat f" / check contents of file f
"123"
,"5"
"99"
q)sum"J"$(0:):f 227  Explanation: Read in the file called f, cast to longs, sum up: sum"J"$read0:f / ungolfed solution
:f / our input file f
"J"\$         / parse strings to longs
sum             / sum it up


Bonus:

The solution in K4 is 10 bytes. Eequivalent to sum value each read0 :f in Q:

+/.:'0::f


## Wumpus, 11 8 bytes

I+0i.
O@


Try it online!

### Explanation

As long as there are numbers left to read, the program loops through the first line:

I   Read a decimal integer from STDIN.
+   Add it to the top of the stack. Initially, the stack is empty, which adds
the first number to an implicit zero.
0   Push 0.
i   Read the next byte. If there are numbers left, this will be a 10 (for the
separating linefeed). Otherwise, we're at EOF and this gives -1.
.   Jump to (0, x), where x is the byte we just read, modulo 2 (because the
program is 2 rows tall). So for a linefeed, this jumps to the beginning
of the first line, and at EOF this jumps to the beginning of the second
line.


Once we run out of numbers to add, control flow goes to the second line:

O   Print the sum as a decimal integer.
@   Terminate the program.


# Flobnar, 16 12 bytes

-4 bytes thanks to @JoKing

+>p*
^@
>&06


Try it online! Requires the -d flag.

As a bonus, this works if no numbers are passed, and supports pretty much any separator other than digits and -.

• 12 bytes – Jo King Aug 17 '18 at 11:05
• @JoKing I have no idea how that works, but ok... – Esolanging Fruit Aug 19 '18 at 7:03

# APL (Dyalog Unicode), 12 bytes

Complete program.

+/⍎⍕⊃⎕NGET⍞1


Try it online!

⍞ read filename from stdin

⊃⎕NGET1 get native file content as list of strings

⍕ stringify (puts two spaces between lines)

⍎ execute (as APL code)

+/ sum

# Sinclair ZX81 (16K only - probably*) File size according to EightyOne - 163** bytes (yes 163!) Byte count undetermined

Firstly, we should make our file, so using direct mode, type:

LET A=123
LET B=5
LET C=99


To make sure that they are there, print them to the screen, as follows:

PRINT A,,B,,C


This should appear on the display:

Now, to save this to file (as the variable stack is saved along with other important memory locations used by the interpreter), simply type:

SAVE "SUM"


If you're using a real ZX81 then press play and record on tape, whilst emulators like EightyOne will create a tape image for you.

Now clear the RAMs with:

RAND USR 0


or:

NEW


Now rewind the tape (or the emulator should auto-detect and start the virtual tape from the beginning), and type:

LOAD "SUM"


So our file is back in memories, so we need to add it together. Simply:

PRINT A+B+C


*I specify 16K because any less and the ZX81 will typically rearrange the memory and this could affect the var stack (mostly to do with collapsing the DFILE), as the DFILE is static with 16K then this should be less of an issue.

**The ZX81 file is saving more than just the VAR stack of three whole variables above, and although each number appears to be an integer, the ZX81 is storing these variables as 24-bit floating point numbers rather than 1 byte integers.

• Utterly brilliant . Let's not mention the spec :) – user9206 Mar 24 '17 at 10:03
• I'm confused what the actual code is. Is that PRINT A+B+C part of it? Would it be invalid then if there are more or less than 3 numbers? – Luis Mendo Mar 24 '17 at 11:45
• The challenge seemed to specifically require a file, and to do that on a ZX81 you need to save your values somewhere. I decided to use the 24-bit floating point variables that I named A, B, and C. I could have POKEd these values to a spare bit of memory but I'm not sure if it'll save. So if you wanted more variables, then you'd need to initialise and declare more variables, so if LET D=321 and that was SAVEd then to add up the file contents, one would PRINT A+B+C+D. I could save to a string but I'd been some way to separate each individual number by a comma, for instance. – Shaun Bebbers Mar 24 '17 at 11:53
• Remember, I initialised and declared the variable values, then saved that to a file before clearing the memory. I then loaded back the file using the ZX81's equivalent of standard in - once the file was loaded, the variables were back in memory, so therefore I could use the PRINT keyword to add up and output the values. – Shaun Bebbers Mar 24 '17 at 11:56
• @ShaunBebbers The same program needs to work for an arbitrary number of values without modification. – AJMansfield Mar 25 '17 at 7:01

# Anyfix, 4 bytes

ɦ€#S


### Explanation

ɦ€#S  Program
ɦ     Exhaust input; read into a list of lines
€    Map:
#        Parse to number
S  Sum


# JavaScript (ES6), 27 bytes

s=>eval(s.split
.join+)


## Try it

f=
s=>eval(s.split
.join+)
oninput=_=>o.innerText=f(i.value);o.innerText=f(i.value=123\n5\n99)
textarea{font-family:sans-serif;height:100px;width:100px;}
<textarea id=i></textarea><pre id=o>

## Explanation

• Takes input as a multiline string via parameter s.
• Splits the string to an array on newlines.
• Joins the array to a string on +.
• Evals the string to give us the sum.

## Alternative, 23 bytes

If we could take each integer as an individual argument of our function then we could do this:

(...a)=>eval(a.join+)


## Alternative, 63 bytes

If we have to take a file name as input then use this version instead:

p=>fetch(p).then(r=>r.text()).then(s=>eval(s.split
.join+))


# Stax, 2 bytes

|+


Run and debug it

Also prints intermediate results, which doesn't appear to be disallowed

# C++, 98 bytes

#include<regex>
namespace std{int::main(){istream_iterator<int>a{cin},b;cout<<accumulate(a,b,0);}}


## Ungolfed

#include <iterator>
#include <numeric>
#include <iostream>

int main()
{
std::istream_iterator<int> first{std::cin};
std::istream_iterator<int> last{};
std::cout << std::accumulate(first, last, 0);
}


We have std::istream_iterator to read input as whitespace-separated integers, and std::accumulate to add them up.

~Ilj~#
>K+O@


Try it online!

# Scheme, 48 bytes

(write(let l((x 0))(if(real? x)(+(l(read))x)0)))


Try it online! (Chicken Scheme, but this works on other schemes as well)

(write ... ) write to STDOUT the result of

• (let l ... ) looping special form named l

• ((x 0)) initially declare x as 0
• (if ... ) if
• (real? x) x is real, i.e. not EOF,
• (+ ... ) add
• (l(read)) the result of this loop called with x set as the value read from STDIN
• x with x
• 0 else give 0