31
\$\begingroup\$

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.

\$\endgroup\$
7
  • 2
    \$\begingroup\$ Is there a trailing newline? Is that newline optional? \$\endgroup\$ Mar 24, 2017 at 6:50
  • 10
    \$\begingroup\$ Hi! I downvoted this challenge because it goes against our community standards for acceptable input/output formats by having a restrictive input format. \$\endgroup\$ Mar 24, 2017 at 15:34
  • 1
    \$\begingroup\$ @AdmBorkBork and I discussed this at length in the chat room. We have agreed to disagree :) \$\endgroup\$
    – user9206
    Mar 24, 2017 at 17:09
  • 25
    \$\begingroup\$ 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. \$\endgroup\$
    – xnor
    Mar 24, 2017 at 18:58
  • 2
    \$\begingroup\$ Why can't function input be used? \$\endgroup\$ Apr 9, 2017 at 21:02

80 Answers 80

2
\$\begingroup\$

Pyke, 4 bytes

zbrs

Try it online!

z    -   input()
 b   -  int(^)
  r  - if no errors: goto start
   s - sum(stack)
\$\endgroup\$
2
\$\begingroup\$

GS2, 2 bytes

Wd

Try it online!

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.
\$\endgroup\$
2
\$\begingroup\$

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.

\$\endgroup\$
2
  • \$\begingroup\$ Do you have to do set s=0 in the beginning? It will work on the first run without it, won't it? \$\endgroup\$ Mar 24, 2017 at 16:14
  • 1
    \$\begingroup\$ @KodosJohnson I'm not sure that's legal in code golf; as I recall the same applies to being able to call a function more than once without the caller resetting global variables to zero in between. \$\endgroup\$
    – Neil
    Mar 24, 2017 at 17:14
2
\$\begingroup\$

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.

\$\endgroup\$
2
\$\begingroup\$

Python 2, 50 45 43 bytes

Pretty self-explanatory.

s=0
try:
    while 1:s+=input()
except:print s

Try it online

\$\endgroup\$
5
  • 2
    \$\begingroup\$ I think any error suffices for break, since programs can terminate in error by default. An unitialized variable would do. \$\endgroup\$
    – xnor
    Mar 23, 2017 at 20:51
  • 4
    \$\begingroup\$ Better yet, the while can be in the try block. \$\endgroup\$
    – xnor
    Mar 23, 2017 at 20:54
  • \$\begingroup\$ Use only 1 space before while 1:. If you're using tabs SE messes them up. \$\endgroup\$ Apr 9, 2017 at 21:03
  • \$\begingroup\$ @CalculatorFeline If you "edit" the post you can see it's a real tab. You can also see it's a real tab on TIO. I prefer tabs to spaces. \$\endgroup\$
    – mbomb007
    Apr 10, 2017 at 3:04
  • \$\begingroup\$ Good to know.`` \$\endgroup\$ Apr 10, 2017 at 21:27
2
\$\begingroup\$

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.

\$\endgroup\$
6
  • \$\begingroup\$ Your 18 byte version is valid. \$\endgroup\$
    – user9206
    Mar 24, 2017 at 6:05
  • \$\begingroup\$ @Lembik Thanks, wasn't 100% sure if the no-extension would be allowed, updated the answer there. \$\endgroup\$
    – colsw
    Mar 24, 2017 at 9:59
  • \$\begingroup\$ If extraneous output is allowed, you can do gc 1|measure -s for 15 \$\endgroup\$ Mar 24, 2017 at 13:23
  • \$\begingroup\$ @Lembik see AdmBorkBork's suggestion, if all the 'extra' text is allowed let me know and I can update my answer, thanks! \$\endgroup\$
    – colsw
    Mar 24, 2017 at 17:07
  • 1
    \$\begingroup\$ @Lembik thanks for clearing that up - i'll leave it as a note anyway as it is interesting. \$\endgroup\$
    – colsw
    Mar 24, 2017 at 17:09
2
\$\begingroup\$

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);}}

Try it Online

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);}}
\$\endgroup\$
2
\$\begingroup\$

Pip, 4 bytes

3 bytes of code, +1 for -r flag.

$+g

Try it online!

$+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.

\$\endgroup\$
2
\$\begingroup\$

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.

\$\endgroup\$
2
  • \$\begingroup\$ Thank you. Can you do it in pdf too? \$\endgroup\$
    – user9206
    Mar 25, 2017 at 11:42
  • \$\begingroup\$ @Lembik I'll see, it's a bit harder to do actual computation in PDF since it only contains a subset of the operators and a bunch of security limitations. \$\endgroup\$ Mar 27, 2017 at 14:56
2
\$\begingroup\$

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
\$\endgroup\$
0
2
\$\begingroup\$

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)}}
\$\endgroup\$
2
\$\begingroup\$

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+

Try it here

    @ O
    ; U
I ! W + . . . .
. . . . . . . .
    . .
    . .
\$\endgroup\$
2
\$\begingroup\$

GNU sed + bc, 34 bytes

:
$!N
$!b
y:\n:+:
s:.*:echo &|bc:e

Try it online!

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

Try it online!

The program does bignum arithmetic, as long as sed can store in memory the unary result.

\$\endgroup\$
2
\$\begingroup\$

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;}

Try it!

Reads from System.in

\$\endgroup\$
2
\$\begingroup\$

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
\$\endgroup\$
2
\$\begingroup\$

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

Try it online!

\$\endgroup\$
2
\$\begingroup\$

Tcl, 33 bytes

puts [expr [join [read stdin] +]]

Try it online!

\$\endgroup\$
0
2
\$\begingroup\$

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...

\$\endgroup\$
1
\$\begingroup\$

Labyrinth, 8 bytes

?+
;,;!@

Try it online!

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.
\$\endgroup\$
1
\$\begingroup\$

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.

Try it here.

\$\endgroup\$
2
  • \$\begingroup\$ Java, the black sheep of the golfing family :) \$\endgroup\$
    – user9206
    Mar 24, 2017 at 8:55
  • 1
    \$\begingroup\$ @Lembik Yep.. I can usually compete with BrainFuck, C# and other longer languages, but Java certainly will never win a golfing contest. The only accepted Java answer I've seen so far was for a [popularity-contest]. But it's still fun to golf in Java imo, and once in a while something is pretty short compared to other submissions - in Java 8 that is :) \$\endgroup\$ Mar 24, 2017 at 10:38
1
\$\begingroup\$

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))

Try it online!

\$\endgroup\$
2
  • \$\begingroup\$ 119 bytes: t=0;with(require('readline').createInterface({input:process.stdin}))on('line',l=>{t-=-l}),on('close',_=>console.log(t)) \$\endgroup\$ Mar 26, 2017 at 17:33
  • \$\begingroup\$ @IsmaelMiguel You can do even better with chaining, so: my answer. \$\endgroup\$ Mar 26, 2017 at 20:27
1
\$\begingroup\$

Julia, 44 bytes

print(sum(map(s->parse(Int,s),readlines())))
\$\endgroup\$
1
  • \$\begingroup\$ A Julia answer is very warmly welcomed! \$\endgroup\$
    – user9206
    Mar 24, 2017 at 13:48
1
\$\begingroup\$

Jellyfish, 24 bytes

p
/
+
j, ,']
1'[J-1
   0

Try it online!

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.

\$\endgroup\$
1
\$\begingroup\$

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!

\$\endgroup\$
1
  • \$\begingroup\$ You could save a few bytes by just wrapping the function in namespace std{ and declaring the function as ::main, rather than using using. \$\endgroup\$ Mar 25, 2017 at 6:57
1
\$\begingroup\$

Scala, 48 bytes

print(io.Source.stdin.getLines.map(_.toInt).sum)
\$\endgroup\$
1
\$\begingroup\$

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))

Try it online!

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))
\$\endgroup\$
1
\$\begingroup\$

REXX, 47 bytes

s=0
pull n
do until n=''
  s=s+n
  pull n
  end
say s
\$\endgroup\$
1
\$\begingroup\$

Alice, 11 bytes

/o
\i@/Hd&+

Try it online!

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.
\$\endgroup\$
1
\$\begingroup\$

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.

Try it online!

\$\endgroup\$
1
\$\begingroup\$

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.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.