| Bytes | Lang | Time | Link |
|---|---|---|---|
| 107 | Pascal | 250609T000000Z | Kai Burg |
| 001 | Thunno 2 S | 230609T145246Z | The Thon |
| 018 | J | 221113T054715Z | south |
| 013 | Juby | 221011T133720Z | Jordan |
| 003 | Vyxal | 221011T064648Z | DialFros |
| 024 | Flurry | 200818T233437Z | Bubbler |
| 048 | Scheme | 191201T082332Z | user4180 |
| 059 | TSQL | 170621T152604Z | BradC |
| 013 | Ahead | 180821T055805Z | snail_ |
| 012 | APL Dyalog Unicode | 180819T145635Z | Adá |
| 012 | Flobnar | 180817T065326Z | Esolangi |
| 098 | C++ | 180817T083113Z | Toby Spe |
| 002 | Stax | 180510T134254Z | vazt |
| 033 | Tcl | 170617T120223Z | sergiol |
| 008 | Wumpus | 180215T134726Z | Martin E |
| 002 | MATL | 170323T220941Z | Luis Men |
| 027 | JavaScript ES6 | 170621T143501Z | Shaggy |
| 014 | q/kdb+ | 180115T220527Z | mkst |
| 015 | Triangular | 170616T172821Z | MD XF |
| 003 | Implicit | 170910T031802Z | MD XF |
| 002 | Ly | 170910T060901Z | LyricLy |
| 004 | Anyfix | 170617T023530Z | hyperneu |
| 006 | Carrot | 170719T093414Z | TheLetha |
| 057 | Lua | 170621T151008Z | Dwayne S |
| 096 | Dart | 170621T150216Z | Dwayne S |
| 019 | QBIC | 170618T184718Z | steenber |
| nan | 170617T145717Z | Twometer | |
| 078 | JavaScript Node.js | 170617T051817Z | Justin M |
| 015 | Ruby | 170324T090616Z | daniero |
| 011 | Alice | 170411T174658Z | Martin E |
| 047 | REXX | 170410T203424Z | idrougge |
| 034 | GNU sed + bc | 170323T224345Z | seshouma |
| 014 | dc | 170327T195212Z | Brian Mc |
| 019 | Awk | 170323T205506Z | Okx |
| 015 | Cubix | 170327T015816Z | MickyT |
| 112 | JavaScript Node.js | 170326T202552Z | Brian Mc |
| 048 | Scala | 170326T193755Z | Brian Mc |
| 146 | Go | 170325T181452Z | Eric Lag |
| 059 | QBasic 4.5 | 170324T161348Z | steenber |
| 011 | PostScript | 170325T064716Z | AJMansfi |
| 004 | Pip | 170325T041925Z | DLosc |
| nan | 170323T205504Z | Brad Gil | |
| 022 | dc | 170325T015626Z | Digital |
| 121 | C# | 170325T024918Z | VisualMe |
| 030 | Pure bash | 170325T011047Z | Digital |
| 018 | Powershell | 170324T003445Z | colsw |
| 022 | PHP | 170323T212250Z | Cave Joh |
| 099 | C++ | 170324T145509Z | Monkah V |
| 043 | Python 2 | 170323T204952Z | mbomb007 |
| 024 | Jellyfish | 170324T135958Z | Martin E |
| 044 | Julia | 170324T134823Z | David Co |
| 017 | MATLAB | 170324T123722Z | Hugh Nol |
| 002 | Actually | 170324T113950Z | user4594 |
| 124 | JavaScript Node.js | 170324T110901Z | alebianc |
| nan | Sinclair ZX81 16K only probably* File size according to EightyOne 163** bytes yes 163! Byte count undetermined | 170324T100232Z | Shaun Be |
| 036 | Pure Bash | 170323T205607Z | betseg |
| 111 | Java 7 | 170324T085217Z | Kevin Cr |
| 009 | Perl 5 | 170324T081710Z | Dada |
| 004 | Brachylog | 170324T072543Z | Fatalize |
| 055 | Batch | 170324T010619Z | Neil |
| 016 | Bash + coreutils | 170323T205524Z | seshouma |
| 008 | Jelly | 170323T223242Z | Dennis |
| 019 | Mathematica | 170323T221552Z | Martin E |
| 007 | Retina | 170323T214557Z | Riley |
| 008 | Labyrinth | 170323T221207Z | Martin E |
| 005 | jq | 170323T221021Z | lynn |
| 028 | Python 3 | 170323T213712Z | Dennis |
| 030 | Python | 170323T211530Z | Riker |
| 002 | GS2 | 170323T213118Z | Dennis |
| 003 | Pyth | 170323T212946Z | Dennis |
| 005 | CJam | 170323T212559Z | Dennis |
| 004 | Pyke | 170323T210814Z | Blue |
| 013 | Paste + bc | 170323T210353Z | Okx |
| 053 | C | 170323T210350Z | orlp |
| 032 | Haskell | 170323T205658Z | nimi |
| 040 | Python 2 | 170323T210023Z | orlp |
| 020 | BrainFlak | 170323T204724Z | Wheat Wi |
| 016 | Vim | 170323T205209Z | DJMcMayh |
| 002 | Japt | 170323T204441Z | ETHprodu |
| 002 | 05AB1E | 170323T204045Z | Okx |
Pascal, 107 B
In Pascal the binding of a file‐type program parameter is implementation‐defined.
The specific way of associating input with “standard input” depends on the implementation, e. g. writing something like /sysfile systdta = (syscmd) (JCL).
program s(input,output);var s,i:integer;begin
s:=0;while not EOF do begin readLn(i);s:=s+i end;write(s)end.
Expanded:
{ The special `program` parameters `input` and `output` are `text`
files. `Text` files are (possibly empty) sequences of (possibly
empty) lines. In conjunction with `text` files, the built‐in
procedures `read` and `readLn` can convert textual representations
of numbers to their respective data `type`s in Pascal. }
program sum(input, output)
var
{ The built‐in data type `integer` comprises all integral
values in the range `−maxInt` through `+maxInt`. The value
of the constant `maxInt` is defined by the implementation. }
sum, i: integer;
begin
{ You need to initialize variables before reading from them. }
sum ≔ 0;
{ Replace with a `repeat` … `until EOF(input)` loop
if it is guaranteed that `input` is non‐empty. }
while not EOF(input) do
begin
{ `ReadLn` is necessary because the other built‐in
procedure `read` cannot read past end‐of‐line
character sequences. }
readLn(input, i);
{ Note that in Pascal the semicolon is a separator.
It can be omitted if you do not separate things. }
sum ≔ sum + i
end;
writeLn(output, sum)
end.
Example invocation:
./sum << EOT
123
5
99
EOT
Example output:
227
J, 18 bytes
1#.0".&>;:@stdin''
1#.0".&>;:@stdin''
stdin'' NB. self-explanatory
@ NB. then
;: NB. split into words, J boxes each int and each LF
&> NB. for every box
0". NB. eval the item as J code and fallback to 0
1#. NB. sum the result
Flurry, 24 bytes
[]{{}[<><<>()>]{}}[<>()]
Run example
$ printf "11\n12\n13" | ./flurry -nii -c "[]{{}[<><<>()>]{}}[<>()]"
36
The integer input mode handles the input format requirement. Then it is straightforward reduction over the stack.
// Reduce the stack by running <pop and add to the current value>
// <stack height> times
main = height pop_add 0
height = []
pop_add = \x. x succ pop = {{}[<><<>()>]{}} // add x y = x succ y
0 = (SK) = [<>()]
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 namedl((x 0))initially declarexas0
(if ... )if
(real? x)xis real, i.e. not EOF,
(+ ... )add
(l(read))the result of this loop called withxset as the value read from STDIN
xwith x
0else give0
T-SQL, 60 59 bytes
SELECT 0a INTO n;BULK INSERT n FROM'd:n'SELECT SUM(a)FROM n
This is the kind of thing that SQL was designed to do, surprised there isn't already an answer for it. Tested on MS SQL 2012.
SELECT 0a INTO n; is slightly shorter than CREATE TABLE n(a INT). Adding a zero row doesn't change the total.
Text file named n (no extension) is located in the current folder on the D: drive. BULK INSERT is shorter and easier than other file import options like SELECT FROM OPENROWSET(BULK) or EXEC xp_cmdshell 'bcp.exe'.
Of course if input is allowed via a pre-existing table, per our normal I/O standards, then this would be trivial (19 bytes):
SELECT SUM(a)FROM n
But of course this challenge is all about the IO...
APL (Dyalog Unicode), 12 bytes
Complete program.
+/⍎⍕⊃⎕NGET⍞1
⍞ read filename from stdin
⊃⎕NGET…1 get native file content as list of strings
⍕ stringify (puts two spaces between lines)
⍎ execute (as APL code)
+/ sum
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 -.
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.
Wumpus, 11 8 bytes
I+0i.
O@
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.
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.
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`+`))
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
read0 / read in a file, break on newlines
"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
Triangular, 15 bytes
(\$]U]P.%p/+U(<
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%
ppops the EOF from the stack.(opens a loop (to add the inputted integers).Upulls 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.Ppops 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).Upulls 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.
Implicit, 4 3 bytes
©1Þ
I'm going to add a builtin for ©1 eventually (e.g. when I'm done working on bitwise). (Just kidding, I'm never going to get around to it.)
Explanation:
©1Þ
©1 consume all input as integers
Þ sum the entire stack
Anyfix, 4 bytes
ɦ€#S
Explanation
ɦ€#S Program
ɦ Exhaust input; read into a list of lines
€ Map:
# Parse to number
S Sum
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
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.
Dart, 96 bytes (non async), 132 bytes (async)
Non async:
import'dart:io';main(){_ s;_ i=0;while((s=stdin.readLineSync())!=null)i+=int.parse(s);print(i);}
Dart allows you to define local variables with types that don't exist when running in uncheck mode (which is the default mode). This program doesn't function in checked mode.
Async:
import'dart:io';import'dart:convert';main()async=>print((await UTF8.decodeStream(stdin)).split("\n").fold(0,(p,e)=>p+int.parse(e)));
The async version is longer, easier to read, and faster than the sync version. It also works in checked mode. UTF8.decodeStream decodes the entire stream into a Future, await waits for this to finish and gives a String, the string is split by line into List, and finally the strings are folded into the final result.
QBIC, 19 bytes
{_?~A=Z|_Xp\p=p+!A!
Explanation
{ DO infinitely
_? Ask for user input, save as A$
~A=Z IF input was nothing (Z$ = "")
|_Xp THEN QUIT, printing the total
\p=p+ ELSE increase the total by
A the given input
! ! cast as a number
Java 7, 109 Bytes
import java.util.*;int x;int s(){Scanner a=new
Scanner(System.in);while(a.hasNext())x+=a.nextInt();return x;}
Reads from System.in
JavaScript (Node.js), 78 bytes
process.stdin.on("data",r=>console.log((""+r).split`
`.reduce((a,v)=>+a+ +v)))
No requires needed for this one, just native NodeJS.
Ruby, 19 15 bytes
Loving that new #sum in Ruby 2.4 :)
p$<.sum(&:to_i)
This program accepts input from either stdin or any filename(s) given as command line argument
Alice, 11 bytes
/o
\i@/Hd&+
This feels a bit suboptimal with all those mirrors (and also because the H could also be a +, possibly allowing reuse there), but so far I've only found a handful of different 11-byte solutions.
Explanation
/o
\i@/...
While it's sometimes possible to shorten it, this seems to be a good pattern for programs which a) one or more integers as input, b) transform them with a linear program in Cardinal mode (i.e. integer processing mode), c) want to output one integer. The instruction pointer (IP) first moves from / to / bouncing through the i which reads all input. Then the ... is executed and the IP wrap around to the wrong. The \ puts the IP again in Ordinal mode where o prints the integer as a decimal string and @ terminates the program. So that's the framework I'm using here.
The core of the program is then just four commands:
H Compute the absolute value of the top of the stack. The reason we're doing this
is that the stack still holds the entire input as a string. But as soon as you
try to pop a value in Cardinal mode, that string gets implicitly converted
to the integers it contains. So in this case, the H itself doesn't really
do anything but it forces the input to be converted. We could also use
+ here and already sum the top two values (if there's only one value it
would get added to an implicit zero, so that's fine).
d Push the stack depth, i.e. the number of integers in the input.
& Execute the next command that many times.
+ Add the top two numbers of the stack. Of course this is one more addition
than we need, but there are only implicit zeros beneath the input so
they don't change the result.
REXX, 47 bytes
s=0
pull n
do until n=''
s=s+n
pull n
end
say s
GNU sed + bc, 34 bytes
:
$!N
$!b
y:\n:+:
s:.*:echo &|bc:e
It is possible to do a shell call from inside sed, and as such I use bc to calculate the sum. Lines 1 to 4 only prepare the input necessary for that calculation. This works for negative numbers as well.
Explanation:
: # start reading loop
$!N # if not EOF, read and append a new input line to pattern
$!b # repeat
y:\n:+: # turn all newlines into pluses
s:.*:echo &|bc:e # shell call to bc with pattern as input (calculates sum)
# implicit printing
Pure GNU sed program: 236 + 1(r flag) = 237 bytes (as promised some time ago)
There are no data types or any math operations in sed. I have tried various methods, but it turns out that concatenating the numbers in unary format and converting the result back to decimal is the simplest way. This works for non-negative integers only, compared to the code above, however this is precisely what the challenge stated in the first place.
G;s:\n::
# concatenate current decimal number with the intermediary unary sum, if any
h;:;s:\w::2g;y:9876543210:87654321\t :;/ /!s:;|$:@:;/\s/!t;x;s:.::;x;G;s:;.*::m;s:\s::g;/\w/{s:@:&&&&&&&&&&:g;t}
# convert the decimal number to unary (using '@' as digit)
y:@:;:
# change unary digit from '@' to ';', to not interfere with above on the next cycle
h;$!d
# store intermediary unary sum and start next reading cycle if input lines left
s:^:0:;/;/{:d;s:^9+:0&:;s:.9*;:/&:;h;s:.*/::;y:0123456789:1234567890:;x;s:/.*::;G;s:\n::;s:;::;/;/td}
# convert final unary sum to decimal (result), plus implicit printing at the end
The program does bignum arithmetic, as long as sed can store in memory the unary result.
dc, 14 bytes
0[+?z2=a]dsaxp
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
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
Cubix, 15 bytes
I have two versions to do this. The first (and longest) is to specification. This will work with non negative integers only. A negative integer will be treated as a end of input, but zeros will be handled correctly.
O<u;Ii?;+...@._
Try it here
Expanded onto the cube
O <
u ;
I i ? ; + . . .
@ . _ . . . . .
. .
. .
This essentially reads in an integer and the seperator. If the separator is negative (EOF or negative) redirect up into a path that will remove two items from the stack, output the already summed results, grab a superfluous input and exit. Otherwise if the input is non negative remove from the stack then sum. This creates a rolling total.
The shorter (8 byte) non-compliant version will handle non-zero integers, but it treats 0 on the stack as the end of input.
@O;UI!W+
@ O
; U
I ! W + . . . .
. . . . . . . .
. .
. .
JavaScript (Node.js), 112 bytes
Improvements upon the other JavaScript answer and comment below it.
a=0
require('readline').createInterface({input:process.stdin}).on('line',l=>a+=+l).on('close',_=>console.log(a))
Given the split module (npm install split), it's much shorter:
JavaScript (Node.js) with split module, 90 bytes
a=0
process.stdin.pipe(require('split')()).on('data',l=>a+=+l).on('end',_=>console.log(a))
Scala, 48 bytes
print(io.Source.stdin.getLines.map(_.toInt).sum)
Go, 146 bytes
package main
import("bufio";"os";"strconv")
func main(){
s:=bufio.NewScanner(os.Stdin)
n:=0
for s.Scan(){m,_:=strconv.Atoi(s.Text())
n+=m
print(n)}}
QBasic 4.5, 61 59 bytes
Since QBasic isn't the greatest with streams, the input is assumed in a file called "a".
Minus 2 bytes because @DLosc showed me an alternate syntax for one of QBasic's most iconic commands. Does QBasic really hold no secrets for you?
OPEN"I",1,"a"
WHILE EOF(1)=0:INPUT#1,b$:x=x+VAL(b$)
WEND:?x
PostScript, 11
Consists of two files. File A: (2 bytes)
0[
File B: (8 bytes tokenized)
]{add}forall =
Invoke as: (1 byte for extra file)
$ gs a inputfile b
This takes advantage of the fact that the input format is also valid PostScript code that just pushes all the numbers on the stack.
This allows it to very cheaply create an array from them over which it can iterate, by using multiple files to place an initial value for the summation and the opening brace on the stack before the input file.
Pip, 4 bytes
3 bytes of code, +1 for -r flag.
$+g
$+g is the standard "sum all inputs" program--read it as fold-plus(arglist). Normally the arglist is taken from command-line arguments. The -r flag takes it from lines of stdin instead.
Perl 6, 13 bytes
say sum lines
Explanation
lines()returns a list of lines from$*INor$*ARGFILESa “magic” command-line input handle.sum(…)was added to Perl 6 to allow[+] Listto be optimized for Positionals that can calculate their sum without generating all of their values like1..100000
(I just thoughtsumwas just too cute here to use[+]like I normally would)say(…)call the.gistmethod on its input, and prints it with an additional newline.
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 `p`rint top-of-stack, then `q`uit 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.
C#, 121 bytes
Java, but no C#? That will not do...
using C=System.Console;class P{static void Main(){int a=0,b;for(;int.TryParse(C.ReadLine(),out b);)a+=b;C.WriteLine(a);}}
Since this score is worse than Java's, we'd better provide a 95 byte context-less function also:
using C=System.Console;int S(){int a=0,b;for(;int.TryParse(C.ReadLine(),out b);)a+=b;return a;}
Formatted and commented:
using C=System.Console;
class P
{
static void Main()
{
int a=0,b; // a is accumulator, b is tempory storage
for(;int.TryParse(C.ReadLine(),out b);) // read a line, try to parse it as an integer (expects a trailing new-line)
a+=b; // add to accumulator
C.WriteLine(a); // print accumulator
}
}
I was really hoping to have some code like the following:
int a=0,b=0,c;
for(;(c=C.Read())>0;)
b=c<15?(a+=b)*0:b*10+c-48;
C.WriteLine(a);
But it just doesn't pay :(
Just for fun, the try...catch solution is also 121 bytes
using C=System.Console;class P{static void Main(){int a=0;try{for(;;)a+=int.Parse(C.ReadLine());}catch{}C.WriteLine(a);}}
Pure bash, 30
read -d_ b
echo $[${b//'
'/+}]
reads the input file in one go into the variableb.-d_tellsreadthat the line delimiter is_instead of newline${b//'newline'/+}replaces the newlines inbwith+echo $[ ... ]arithmetically evaluates the resulting expression and outputs it.
Powershell, 18 Bytes
(gc 1)-join"+"|iex
this assumes the file is named '1' with no extension.
alternate 24 byte version, takes filename as input:
(gc "$args")-join"+"|iex
explanation:
( get content of the file "$args" ) then -join the lines together with a "+" to form a valid-syntax sum, then | invoke expression to calculate it as if it was typed into the console directly.
if output is allowed in the following format:
Count : 3
Average :
Sum : 227
Maximum :
Minimum :
Property :
then gc 1|measure -s is a valid 15 byte solution, thanks to @AdmBorkBork for pointing that out.
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.
C++, 99 Bytes
using namespace std;int main(){string a;int b=0;while(1){getline(cin,a);cout<<(b+=stoi(a))<<"\n";}}
Not my finest work, and there's probably a far better way to go about doing this. Still, I figured that using a string was the optimal way of doing things, seeing as I felt conversions with 'cin' would take up a vast majority of my code otherwise.
Enjoy!
Python 2, 50 45 43 bytes
Pretty self-explanatory.
s=0
try:
while 1:s+=input()
except:print s
Jellyfish, 24 bytes
p
/
+
j, ,']
1'[J-1
0
Explanation
Reading input isn't very flexible in Jellyfish. In particular, there's no easy way to read a variable number of integers from STDIN, except as a list literal. So the majority of this code is input.
The shortest way I've found is to read all of STDIN as a string, then wrap it in [...] and then evaluate the string. Thankfully, Jelly's parser only looks for whitespace as a separator in lists, not specifically for space characters. So the linefeed separation required by the challenge works.
So let's build up the code from the bottom:
J-1
0
Read all input.
,']
J-1
0
Append ].
, ,']
'[J-1
0
Prepend [.
j, ,']
1'[J-1
0
Evaluate.
/
+
j, ,']
1'[J-1
0
Fold addition (in other words, sum).
p
/
+
j, ,']
1'[J-1
0
Print the result.
Julia, 44 bytes
print(sum(map(s->parse(Int,s),readlines())))
MATLAB: 17 bytes
sum(dlmread('x'))
Assumes a file named 'x' in current directory. dlmread reads numeric values from a file using delimiters - if no delimiter is specified as the second argument, it will infer from the file type. It successfully infers \n as the delimiter in a file as specified by the question, then uses sum to add them up.
Actually, 2 bytes
kΣ
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)
JavaScript (Node.js), 124 bytes
t=0;
r=require('readline').createInterface({input:process.stdin});
r.on('line',l=>{t-=-l});
r.on('close',()=>console.log(t))
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
And the answer is:
*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.
Pure Bash, 37 36 bytes
Thanks to @KevinCruijssen for a byte!
while read a;do((b+=a));done;echo $b
Java 7, 111 bytes
import java.util.*;int c(){Scanner c=new Scanner(System.in);int r=0;for(;c.hasNext();r+=c.nextInt());return r;}
Takes the input from STDIN.
Perl 5, 9 bytes
8 bytes of code + -p flag.
$\+=$_}{
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.
Batch, 55 bytes
@set s=0
@for /f %%n in (%1)do @set/as+=%%n
@echo %s%
Takes the file to be summed as a command-line parameter.
Bash + coreutils, 16 bytes
xargs|tr \ +|bc
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.
Jelly, 9 8 bytes
ƈFпFỴVS
STDIN isn't really Jelly's thing...
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.
Mathematica, 19 bytes
Assumes Mathematica's notebook environment.
Tr[#&@@@Import@"a"]
Expects the input to be in a file a.
Retina, 11 7 bytes
-4 thanks to Martin Ender
.*
$*
1
Convert to unary:
.*
$*
Count the number of 1s:
1
Labyrinth, 8 bytes
?+
;,;!@
The left-most 2x2 block is the main loop:
? Read integer.
+ Add to running total (initially zero).
, Read character. 10 as long as there is another input, -1 at EOF which will
exit the loop.
; Discard the 10.
Once we hit EOF, the IP moves east from the ,.
; Discard the -1.
! Output the sum.
@ Terminate the program.
Python 3, 28 bytes
print(sum(map(int,open(0))))
Taken from this tip. I've been told this won't work on Windows.
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)])
GS2, 2 bytes
Wd
How it works
(implicit) Read all input from STDIN an push it as a string.
W Extract all integers, pushing a single array.
For input x, this executes map(int, re.findall(r'-?\d+', x)) internally.
d Take the sum.
CJam, 5 bytes
q~]1b
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.
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
Another shell answer!
C, 53 bytes
r;main(i){for(;~scanf("%d",&i);r+=i);printf("%d",r);}
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
Python 2, 40 bytes
import sys;print sum(map(int,sys.stdin))
Brain-Flak, 20 bytes
(([]){[{}]{}([])}{})
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.
(([]){[{}]{}([])}{})
Vim, 16 bytes/keystrokes
:%s/\n/+
C<C-r>=<C-r>"<C-h>
Since V is backwards compatible, you can Try it online!
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


