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? – the dark wanderer 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

05AB1E, 2 bytes

|O

Explanation:

|   Get input as array
O  Sum

Try it online!

• That's ridiculous :) – user9206 Mar 23 '17 at 20:41
• Does this read from standard in? – user9206 Mar 23 '17 at 20:50
• @Lembik it does. – Okx Mar 24 '17 at 8:38
• I believe your 2 byte answer was first. You are the winner! (Unless someone finds a 1 byte answer.) – user9206 Mar 24 '17 at 13:38
• @Lembik Or a 0 byte answer.... – Comrade SparklePony Mar 24 '17 at 15:29

Bash + coreutils, 16 bytes

xargs|tr \  +|bc

Try it online!

There are two spaces after the \. This works for negative numbers as well.

Explanation:

xargs             # known trick to turn newlines into spaces, while adding a
#trailing newline when printing the result (needed for bc)
|tr \  +          # turn spaces into '+'s
|bc               # calculates the sum

You may wonder why tr \\n +|bc isn't better, since it turns newlines directly into '+'s. Well, that has 2 unforeseen errors:

• if the input has a trailing newline, then it is converted to a trailing '+', hence there is no number after it to perform the addition
• and the most weird issue is that bc requires a trailing newline after the input, but you just replaced all of the input newlines with '+'s.
• I like this. It's nice and clever. – user9206 Mar 23 '17 at 21:04
• Could you use tr \\n + Instead without xargs? – user9206 Mar 23 '17 at 23:03
• @Lembik Do you mean tr \\n +|bc? If so, then please see the updated explanation. Good question. – seshoumara Mar 24 '17 at 0:50
• paste -s -d+|bc is 15 bytes – David Conrad Mar 24 '17 at 13:29
• @Lembik Didn't considered that case, but fortunately the script still works. xargs|tr \ + in this case does nothing, and bc receives the number and prints it back. – seshoumara Mar 24 '17 at 15:36

MATL, 2 bytes

Us

This expects the input in a text file called defin.

Gif or it didn't happen:

Or try it online! (thanks to Dennis for the set-up!)

Explanation

When a MATL program is run, if a file called defin is found (the name refers to "default input"), its contents are automatically loaded as text and pushed to the stack as a string before executing the code.

Function U evaluates the string to convert it to a column vector of numbers, and s computes the sum, which is implicitly displayed.

Japt, 2 bytes

Nx

Explanation

Implicit: parse STDIN into array of numbers, strings, and arrays
N    Get the resulting parsed array.
x   Sum.
Implicit: output result of last expression

Try it online!

Paste + bc, 13 bytes

paste -sd+|bc

Explanation:

paste -s        Take one line at a time from input
d+      Joining by '+'
|bc   Pass as expression to bc

• Very neat and tidy. – user9206 Mar 23 '17 at 21:05
• Ooh, I had paste -s -d+|bc and didn't realize I could consolidate the switches. Neat! – David Conrad Mar 24 '17 at 13:31

Perl 6, 13 bytes

say sum lines

Try it

Explanation

• lines() returns a list of lines from $*IN or$*ARGFILES a “magic” command-line input handle.
• sum(…) was added to Perl 6 to allow [+] List to be optimized for Positionals that can calculate their sum without generating all of their values like 1..100000
(I just thought sum was just too cute here to use [+] like I normally would)
• say(…) call the .gist method on its input, and prints it with an additional newline.
• What is it perl 5? – user9206 Mar 23 '17 at 21:02
• this reads like lolcode – Bryan Boettcher Mar 23 '17 at 21:58
• @Lembik it is clearly labeled as Perl 6, which is a sister language to Perl 5. – Brad Gilbert b2gills Mar 23 '17 at 22:00
• There was a typo. I meant what is it in Perl 5? – user9206 Mar 23 '17 at 22:10
• Well $a+=$_ for <>;print $a works in Perl 5, but there may be a shorter way. – Brad Gilbert b2gills Mar 23 '17 at 22:14 C, 53 bytes r;main(i){for(;~scanf("%d",&i);r+=i);printf("%d",r);} • C showing its credentials again :) – user9206 Mar 23 '17 at 21:04 • I feel like there should be a shorter way, but I don't see it :) – Digital Trauma Mar 25 '17 at 1:41 Python 3, 28 bytes print(sum(map(int,open(0)))) Taken from this tip. I've been told this won't work on Windows. Try it online! • I learned something new! – user9206 Mar 23 '17 at 22:18 Retina, 11 7 bytes -4 thanks to Martin Ender .*$*
1

Try it online!

Convert to unary:

.*
$* Count the number of 1s: 1 • Interesting how Retina, as a regex based language, can do the sum in fewer bytes than the shortest bash answer posted so far. +1 – seshoumara Mar 23 '17 at 21:56 • Is this reading from standard in? – user9206 Mar 23 '17 at 22:34 • @Lembik Yes it is. – Riley Mar 23 '17 at 22:38 • If input in unary was allowed, it'd be only one byte. – mbomb007 Mar 24 '17 at 14:06 • @mbomb007 I already tried that in sed. – Riley Mar 24 '17 at 14:07 Brain-Flak, 20 bytes (([]){[{}]{}([])}{}) Try it online! Explanation This is a golf off of a solution made by Riley in chat. His solution was: ([])({<{}>{}<([])>}{}) If your familiar with Brain-Flak this is pretty self-explanatory. It pushes the stack height and pops one value as it counts down, at the end it pushes the sum of all the runs. It is a pretty good golf but he zeros both {} and ([]) however these will have a values that only differ by one so if instead we remove the masks and make one of the two negative they should nearly cancel out. ([])({[{}]{}([])}{}) Since they always differ by one we have the unfortunate circumstance where our answer is always off by the stack height. In order to remedy this we simply move the beginning of the push to encompass the first stack height. (([]){[{}]{}([])}{}) • I thought of it as the negative pop cancels the previous height pushed (from before the loop, or the end of the previous time through), and the last height is 0 so it can be ignored. – Riley Mar 23 '17 at 20:51 Python 2, 40 bytes import sys;print sum(map(int,sys.stdin)) R,11 bytes sum(scan()) scan takes the input, one number per line. And sum, well, sums. Perl 5, 9 bytes 8 bytes of code + -p flag.$\+=$_}{ Try it online! With -p, the input is read one line at a time, stored in$_ each time. We use $\ as accumulator, because thanks to -p flag, it's implicitly printed at the end. The unmatched }{ are used so -p flag only prints$\ once at the end instead of printing $_ and$\ at each line it reads like it normally does.

• I can't even parse it! :) Explanation please. – user9206 Mar 24 '17 at 8:23
• @Lembik Here you go. – Dada Mar 24 '17 at 8:28
• The unmatched parenthesise part is very obscure! – user9206 Mar 24 '17 at 8:31
• @Lembik Those aren't parenthesizes... They're either French or Curly Braces depends on who you ask, but they definitely are not )( – CraigR8806 Mar 24 '17 at 14:25
• @Lembik accolades, apparently. – Michael Vehrs Mar 27 '17 at 9:40

Pure Bash, 37 36 bytes

Thanks to @KevinCruijssen for a byte!

while read a;do((b+=a));done;echo $b Try it online! • Very nice and clean. – user9206 Mar 23 '17 at 21:03 • I never program in Bash, but isn't it possible to remove the space between do ((? The TIO seems to work. – Kevin Cruijssen Mar 24 '17 at 8:42 • @KevinCruijssen Yeah, it seems like it works. I use zsh as my daily shell and it doesn't work in zsh without a space, I just assumed it wouldn't work in Bash but apparently it does. – betseg Mar 24 '17 at 9:25 Haskell, 32 bytes interact$show.sum.map read.lines

interact collects the whole input from stdin, passes it to the function given as its argument and prints the string it gets back from this function. The function is:

lines   -- split input into list of lines at nl
map read      -- convert every line to a number (read is polymorphic,
-- but as want to sum it later, the type checker knows
-- it has to be numbers)
sum             -- sum the list of numbers
show                -- convert back to string
• This makes me really like Haskell. In Scala, I have to do lines.map(_.toInt) because sum expects some sort of numeric implicit conversion from String or in this case an explicit one. – Stefan Aleksić Mar 24 '17 at 14:52

PHP, 22 bytes

<?=array_sum(file(t));

This assumes there is a file named "t" with a list of integers.

file() opens a file and returns an array with each line stored a separate element in the array. array_sum() sums all the elements in an array.

Awk, 19 bytes

{s+=$1}END{print s} Explanation: {s+=$1}                For all lines in the input, add to s
END             End loop
{print s}    Print s
• "Explanation coming soon™" That'd be my new catchphrase if it weren't trademarked... – ETHproductions Mar 23 '17 at 20:55
• In the language of awk, your answer is actually only 19 bytes: {s+=$1}END{print s} :) – Digital Trauma Mar 25 '17 at 1:39 dc, 14 bytes 0[+?z2=a]dsaxp Try it online! Explanation: [ ] sa # recursive macro stored in register a, does the following: + # - sum both numbers on stack # (prints to stderr 1st time since there's only 1) ? # - read next line, push to stack as number z # - push size of stack 2 # - push 2 =a # - if stack size = 2, ? yielded something, so recurse # - otherwise end macro (implicit) 0 # push 0 (accumulator) d # duplicate macro before storing it x # Call macro p # The sum should be on the stack now, so print it CJam, 5 bytes q~]1b Try it online! How it works q e# Read all input from STDIN. ~ e# Evaluate that input, pushing several integers. ] e# Wrap the entire stack in an array. 1b e# Convert from base 1 to integer. e# :+ (reduce by sum) would work as well, but 1b handles empty arrays. • How does 1b sum numbers? – Esolanging Fruit Jun 17 '17 at 6:33 • CJam doesn't require a canonical representation for digits-to-integer conversion; [<x> <y> <z> <w>]<b>b simply computes b³x + b²y + bz + w. When b = 1, this gives x + y + z + w. – Dennis Jun 17 '17 at 6:41 Python, 38 30 bytes lambda n:sum(map(int,open(n))) In python, files are opened by open('filename') (obviously). They are, however, iterables. Each time you iterate through the file, you get the next line. So map iterates over each list, calling int on it, and then sums the resulting list. Call with the filename as input. (i.e. f('numbers.txt')) 8 bytes saved by using map(int, open(n)) instead of a list comprehension. Original code: lambda n:sum([int(i)for i in open(n)]) • I believe that you can also do this with standard input by calling 'open(0)'. Not sure if that can be used to shorten your answer. – cole Mar 24 '17 at 0:01 • @Cole dennis already has that solution, so I'll leave my answer like this. – Rɪᴋᴇʀ Mar 24 '17 at 0:06 • My mistake, sorry about that; I didn't read all the way through before coming to your answer. – cole Mar 24 '17 at 1:31 • @Cole it's okay, I don't mind. – Rɪᴋᴇʀ Mar 24 '17 at 2:29 Mathematica, 19 bytes Assumes Mathematica's notebook environment. Tr[#&@@@Import@"a"] Expects the input to be in a file a. • It's a crazy language :) – user9206 Mar 23 '17 at 22:20 • @Lembik normal people would write this very readably as Total @ Flatten @ Import @ "a" or even "a" // Import // Flatten // Total. ;) – Martin Ender Mar 23 '17 at 22:32 • Wouldn't Tr[#&@@@Import@#]& also be allowed? – ngenisis Mar 24 '17 at 18:27 Jelly, 9 8 bytes ƈFÐ¿FỴVS STDIN isn't really Jelly's thing... Try it online! How it works ƈFÐ¿FỴVS Main link. No arguments. Implicit argument: 0 Ð¿ While loop; while the condition returns a truthy value, execute the body and set the return value to the result. Collect all results (including 0, the initial return value) in an array and return that array. ƈ Body: Yield a character from STDIN or [] if the input is exhausted. F Condition: Flatten, mapping 0 to [], '0' to "0", and [] to [] (falsy). F Flatten the result. Ỵ Split at newlines. V Evaluate the resulting strings. S Take the sum. • The second F could be a as well, for clarity. – Erik the Outgolfer Mar 24 '17 at 10:09 Brachylog, 4 bytes ṇịᵐ+ Try it online! Explanation ṇ Split the Input on linebreaks ịᵐ Map: String to Integer + Sum Pure bash, 30 read -d_ b echo$[${b//' '/+}] Try it online. • reads the input file in one go into the variable b. -d_ tells read that the line delimiter is _ instead of newline •${b//'newline'/+} replaces the newlines in b with +
• echo $[ ... ] arithmetically evaluates the resulting expression and outputs it. • +1 Very nice. Is the trailing newline of a input file read as well? I ask because if it is replaced by '+', the$[] section will error due to a trailing '+'. – seshoumara Mar 25 '17 at 7:48
• @seshoumara It appears that read discards final trailing newlines, even though the line delimiter is overridden to _. This is perhaps a caveat of read, but it works well for this situation. – Digital Trauma Mar 25 '17 at 21:35
• I am always happy to see a pure bash solution. – user9206 Mar 26 '17 at 20:03

Vim, 16 bytes/keystrokes

:%s/\n/+
C<C-r>=<C-r>"<C-h>

Since V is backwards compatible, you can Try it online!

• Is this either reading from standard in or from a file? – user9206 Mar 23 '17 at 22:39
• Yeah, Vim might not be allowed...:( – CalculatorFeline Apr 9 '17 at 21:03

Pyth, 3 bytes

s.Q

Try it online!

.Q  Read all of standard input, evaluating each line.
s    Take the sum.

jq, 5 bytes

add, plus the command line flag -s.

For example:

% echo "1\n2\n3\n4\n5" | jq -s add
15
• 6 bytes. Since -sadd won't work, count the space. – agc Mar 25 '17 at 16:37
• @agc Correct me if I'm wrong but the code itself is add (3 bytes) and you have to add 2 bytes for the -s flag. The space doesn't count as the code or the flag: it's the command line separator used by the language. – caird coinheringaahing Mar 28 '17 at 21:01
• @ThisGuy, Well the -s flag is short for "--slurp", (read the entire input stream into a large array and run the filter just once), which changes both how jq interprets the input data, and how it runs the code. It's not like the -ein sed which merely tells sed that the subsequent string is code. The -s is more like a part of the jq language itself, and therefore that 6th byte space would be too. – agc Mar 29 '17 at 4:01

Actually, 2 bytes

Try it online!

Explanation:

kΣ
(implicit input - read each line, evaluate it, and push it to the stack)
k   pop all stack elements and push them as a list
Σ  sum
(implicit output)

dc, 22

[pq]sq0[?z2>q+lmx]dsmx

This seems rather longer than it should be, but it is tricky to decide when the end of the file is reached. The only way I can think of to do this is check the stack length after the ? command.

[pq]                    # macro to print top-of-stack, then quit the program
sq                  # save the above macro in the q register
0                 # push 0 to the stack.  Each input number is added to this (stack accumulator)
[         ]      # macro to:
?               # - read line of input
z              # - push stack length to stack
2             # - push 2 to the stack
>q           # - if 2 > stack length then invoke macro stored in q register
+          # - add input to stack accumulator
lmx       # - load macro stored in m register and execute it
d     # duplicate macro
sm   # store in register m
x  # execute macro

Note the macro m is called recursively. Modern dc implements tail recursion for this sort of thing, so there should be no worries about overflowing the stack.

• Welcome to PPCG! Please note that if there isn't enough explanations it will go through the low quality posts filter. – Matthew Roh Mar 25 '17 at 2:40
• @SIGSEGV no welcome necessary - I've been here a while ;-). Yep, I was writing my explanation while you commented. See edit. – Digital Trauma Mar 25 '17 at 3:22
• I owe you a byte for the trick of duplicating the macro before storing it. – Brian McCutchon Mar 27 '17 at 20:01

Pyke, 4 bytes

zbrs

Try it online!

z    -   input()
b   -  int(^)
r  - if no errors: goto start
s - sum(stack)