Sum a Column of Integers Back to the Win32 Shootout
Back to dada's perl lab

[The Original Shootout]   [NEWS]   [FAQ]   [Methodology]   [Platform Details]   [Acknowledgements]   [Scorecard]  
All Source For Sum a Column of Integers
sumcol.awka
# $Id: sumcol.gawk,v 1.2 2000/10/07 08:41:44 doug Exp $
# http://www.bagley.org/~doug/shootout/

BEGIN { delete ARGV; tot = 0 }
{ tot += $1 }
END { print tot }
sumcol.bcc
/* -*- mode: c -*-
 * $Id: sumcol.gcc,v 1.3 2000/12/24 05:43:53 doug Exp $
 * http://www.bagley.org/~doug/shootout/
 */

#include <stdio.h>
#include <stdlib.h>

#define MAXLINELEN 128

int
main() {
    int sum = 0;
    char line[MAXLINELEN];

    while (fgets(line, MAXLINELEN, stdin)) {
    sum += atoi(line);
    }
    printf("%d\n", sum);
    return(0);
}

sumcol.bigforth
\ -*- mode: forth -*-
\ $Id: sumcol.bigforth,v 1.1 2001/06/24 22:23:53 doug Exp $
\ http://www.bagley.org/~doug/shootout/

256 constant max-line
create line-buffer max-line 1 + allot

: sumcol 
    0
    begin
    0.0 line-buffer
    line-buffer max-line stdin read-line throw
    while
    >number drop drop d>s +
    repeat
    drop drop drop drop 1 u.r cr ;

sumcol

bye
sumcol.cim
% $Id: sumcol.cim,v 1.0 2002/10/29 13:41:00 dada Exp $
external class UNIX;
begin

    integer i, tot;
    inspect SysIn do
    while not SysIn.LastItem do
    begin
        i := InInt;
        tot := tot + i;
    end;
    OutInt(tot, 0);
    OutImage;
end
sumcol.csharp
// $Id: sumcol.csharp,v 1.0 2002/02/14 11:20:00 dada Exp $
// http://dada.perl.it/shootout/

using System;

class App {
    public static int Main(String[] args) {
        int sum = 0;

        for (String line = Console.In.ReadLine(); line != null; line = Console.In.ReadLine()) {
            sum += System.Convert.ToInt32(line);
        }
        Console.WriteLine(sum.ToString() + "\n");
        return(0);
    }
}
sumcol.cygperl
#!/usr/local/bin/perl
# $Id: sumcol.perl,v 1.4 2000/10/07 08:41:44 doug Exp $
# http://www.bagley.org/~doug/shootout/

use integer;
shift;
while (<>) { $tot += $_ }
print "$tot\n";
sumcol.delphi
program sumcol;


var
  num, tot: integer;
begin
  tot:=0;
  while not Eof(input) do begin
    readLn(input, num);
    tot := tot + num;
  end;
  WriteLn(tot);
end.

sumcol.erlang
%%% -*- mode: erlang -*-
%%% $Id: sumcol.erlang,v 1.2 2000/12/31 18:56:43 doug Exp $
%%% http://www.bagley.org/~doug/shootout/

-module(sumcol).
-export([main/0, main/1]).


main() -> main(['1']).
main(Args) ->
    io:put_chars( sumcol( io:fread( '', "~d" ), 0) ),
    halt(0).

sumcol( eof, Sum ) ->
        io_lib:format( "~w~n", [Sum] );
sumcol( {ok, [N]}, Sum ) ->
    io:put_chars( io_lib:format( "~w~n", [Sum] ) ),
    sumcol( io:fread( '', "~d" ), Sum + N ).
sumcol.fpascal
program sumcol;

var
    num, tot: longint;
begin
    While Not Eof(input) Do
    begin
        ReadLn(input, num);    
        tot := tot + num;
    end;
    WriteLn(tot);
end.
sumcol.gawk
# $Id: sumcol.gawk,v 1.2 2000/10/07 08:41:44 doug Exp $
# http://www.bagley.org/~doug/shootout/

BEGIN { delete ARGV; tot = 0 }
{ tot += $1 }
END { print tot }
sumcol.gcc
/* -*- mode: c -*-
 * $Id: sumcol.gcc,v 1.3 2000/12/24 05:43:53 doug Exp $
 * http://www.bagley.org/~doug/shootout/
 */

#include <stdio.h>
#include <stdlib.h>

#define MAXLINELEN 128

int
main() {
    int sum = 0;
    char line[MAXLINELEN];

    while (fgets(line, MAXLINELEN, stdin)) {
    sum += atoi(line);
    }
    printf("%d\n", sum);
    return(0);
}

sumcol.gforth
\ -*- mode: forth -*-
\ $Id: sumcol.gforth,v 1.2 2001/05/24 03:54:30 doug Exp $
\ http://www.bagley.org/~doug/shootout/

256 constant max-line
create line-buffer max-line 1 + allot

: sumcol 
    0
    begin
    0.0 line-buffer
    line-buffer max-line stdin read-line throw
    while
    >number drop drop d>s +
    repeat
    drop drop drop drop 1 u.r cr ;

sumcol

bye \ th-th-that's all folks!
sumcol.ghc
-- $Id: sumcol.ghc,v 1.4 2001/02/24 23:49:59 doug Exp $
-- http://www.bagley.org/~doug/shootout/
-- from Julian Assange

module Main where
import Numeric(readDec)

main = interact (flip (++) "\n" . show . sum . nums . lines)
       where
       nums  = map (fst . head . readDec)
sumcol.gnat
-- $Id: sumcol.gnat,v 1.0 2003/06/11 12:06:00 dada Exp $
-- http://dada.perl.it/shootout/
-- Ada 95 code by C.C.

with Text_IO, Ada.Strings.Fixed, Ada.IO_Exceptions;

procedure SumCol is
   package IE renames Ada.IO_Exceptions;
   package AS renames Ada.Strings;

   function Read_Line return String is
      Buf      : String (1 .. 4096);
      Last     : Natural;
   begin    --  (End_Error here (in ObjectAda) on unusual missing final "\n")
      Text_IO.Get_Line (Text_IO.Standard_Input, Item => Buf, Last => Last);
      if Last < Buf'Last or else
                     Text_IO.End_Of_File (Text_IO.Standard_Input) then
         return Buf (1 .. Last);
      else
         return Buf & Read_Line;
      end if;
   end Read_Line;

   Sum         : Integer := 0;
begin
   while not Text_IO.End_Of_File loop
      declare
         Line     : String := AS.Fixed.Trim (Read_Line, Side => AS.Right);
      begin
         Sum := Sum + Integer'Value (Line);  --  Fail 0 or 2 numbers per line
      end;
   end loop;
   Text_IO.Put_Line (AS.Fixed.Trim (Natural'Image (Sum), Side => AS.Left));
exception                        --  Catch error from Get_Line Integer'Value
   when Constraint_Error | IE.Device_Error | IE.End_Error =>
      Text_IO.Put_Line ("> Error near line" &
               Text_IO.Count'Image (Text_IO.Line));
end SumCol;

sumcol.guile
#!/usr/local/bin/guile \
-e main -s
!#

;;; $Id: sumcol.guile,v 1.4 2001/02/10 13:50:34 doug Exp $
;;; http://www.bagley.org/~doug/shootout/
;;; from Brad Knotwell

(define (main args)
  (let ((sum 0))
    (do ((myInt (read-line) (read-line)))
    ((eof-object? myInt) (write-line sum))
      (set! sum (+ sum (string->;number myInt))))))
sumcol.ici
// $Id: sumcol.ici,v 1.0 2003/01/03 11:23:00 dada Exp $
// http://dada.perl.it/shootout
//
// contributed by Tim Long

count := 0;
while (l = getline())
    count += int(l);
printf("%d\n", count);
sumcol.icon
# -*- mode: icon -*-
# $Id: sumcol.icon,v 1.2 2000/12/17 23:40:20 doug Exp $
# http://www.bagley.org/~doug/shootout/

procedure main(argv)
    sum := 0
    while(sum +:= read())
    write(sum)
end
sumcol.java
// $Id: sumcol.java,v 1.2 2000/10/07 08:41:44 doug Exp $
// http://www.bagley.org/~doug/shootout/

import java.io.*;
import java.util.*;
import java.text.*;

public class sumcol {
    public static void main(String[] args) {
    int sum = 0;
    String line;
        try {
            BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
            while ((line = in.readLine()) != null) {
        sum = sum + Integer.parseInt(line);
            }
        } catch (IOException e) {
            System.err.println(e);
            return;
        }
    System.out.println(Integer.toString(sum));
    }
}
sumcol.lcc
/* -*- mode: c -*-
 * $Id: sumcol.gcc,v 1.3 2000/12/24 05:43:53 doug Exp $
 * http://www.bagley.org/~doug/shootout/
 */

#include <stdio.h>
#include <stdlib.h>

#define MAXLINELEN 128

int
main() {
    int sum = 0;
    char line[MAXLINELEN];

    while (fgets(line, MAXLINELEN, stdin)) {
    sum += atoi(line);
    }
    printf("%d\n", sum);
    return(0);
}

sumcol.lua
-- $Id: sumcol.lua,v 1.2 2000/10/07 08:41:44 doug Exp $
-- http://www.bagley.org/~doug/shootout/

sum = 0
line = read()
while line ~= nil do
    sum = sum + line
    line = read()
end
write(sum, "\n")
sumcol.lua5
-- $Id: sumcol.lua,v 1.2 2000/10/07 08:41:44 doug Exp $
-- http://www.bagley.org/~doug/shootout/
-- contributed by Roberto Ierusalimschy

local sum = 0
for line in io.lines() do
  sum = sum + line
end
print(sum)

sumcol.mawk
# $Id: sumcol.mawk,v 1.1 2001/04/26 17:02:01 doug Exp $
# http://www.bagley.org/~doug/shootout/

BEGIN { delete ARGV; tot = 0 }
{ tot += $1 }
END { print tot }
sumcol.mercury
%% $Id: sumcol.mercury,v 1.3 2001/05/13 01:22:35 doug Exp $
%% http://www.bagley.org/~doug/shootout/

:- module mytest.

:- interface.

:- import_module io.

:- pred main(io__state :: di, io__state :: uo) is det.

:- implementation.

:- import_module string, int.

main -->
    io__read_line_as_string(IOResult),
    sumcol(IOResult, 0).

:- pred sumcol(io__result(string)::in, int::in, io__state::di, io__state::uo) is det.

sumcol(IOResult, Sum) -->
    ( { IOResult = ok(LineIn) },
        { chomp(LineIn, Line) },
    io__read_line_as_string(NewIOResult),
    ( if { string__to_int(Line, N) } then
        sumcol(NewIOResult, Sum + N)
      else
        sumcol(NewIOResult, Sum)
    )
    ; { IOResult = eof },
        io__write_int(Sum),
    io__write_string("\n")
    ; { IOResult = error(_Error) },
    io__write_string("Error reading file!")
    ).

:- pred chomp(string::in, string::out) is det.

chomp(InStr, OutStr) :-
    ( if string__remove_suffix(InStr, "\n", NewStr) then
    OutStr = NewStr
      else
    OutStr = InStr
    ).
sumcol.mingw32
/* -*- mode: c -*-
 * $Id: sumcol.gcc,v 1.3 2000/12/24 05:43:53 doug Exp $
 * http://www.bagley.org/~doug/shootout/
 */

#include <stdio.h>
#include <stdlib.h>

#define MAXLINELEN 128

int
main() {
    int sum = 0;
    char line[MAXLINELEN];

    while (fgets(line, MAXLINELEN, stdin)) {
    sum += atoi(line);
    }
    printf("%d\n", sum);
    return(0);
}

sumcol.nice
/* The Great Win32 Language Shootout http://dada.perl.it/shootout/ 
   contributed by Isaac Gouy (Nice novice)

To compile:	
   nicec --sourcepath=.. -d=. -a sumcol.jar sumcol

To run:
   java -jar sumcol.jar < input.txt > out.txt
*/


import java.io.*;

void main(String[] args){
   int sum = 0;

   try {
      BufferedReader reader = bufferedStdInReader();
      ?String line;
      while (( line = reader.readLine()) != null)
         sum += Integer.parseInt(line);
   } 
   catch (IOException e) { 
      System.err.println(e); 
   }

   println(sum);
}


BufferedReader bufferedStdInReader() = 
   new BufferedReader(new InputStreamReader(System.in));
sumcol.ocaml
(*
 * $Id: sumcol.ocaml,v 1.6 2001/01/14 15:26:28 doug Exp $
 * http://www.bagley.org/~doug/shootout/
 * from Markus Mottl
 *)

let sum = ref 0
let rec loop () = sum := !sum + read_int (); loop ()
let _ = try loop () with End_of_file -> Printf.printf "%d\n" !sum
sumcol.ocamlb
(*
 * $Id: sumcol.ocaml,v 1.6 2001/01/14 15:26:28 doug Exp $
 * http://www.bagley.org/~doug/shootout/
 * from Markus Mottl
 *)

let sum = ref 0
let rec loop () = sum := !sum + read_int (); loop ()
let _ = try loop () with End_of_file -> Printf.printf "%d\n" !sum
sumcol.oz
%%% $Id: fibo.oz,v 1.0 2002/03/12 13:35:00 dada Exp $
%%% http://dada.perl.it/shootout/
functor
import 
    System(printInfo)
    Application(exit)
    Open(text file)
    OS
define
class TextFile  
  from Open.file Open.text  
end 

fun {SumLines FILE SUM}
    {System.printInfo "file.atEnd="}
    if {FILE atEnd($)} == true then
        {System.printInfo "Y"}
    else
        {System.printInfo "N"}
    end
    {System.printInfo "\n"}
    case {FILE getS($)} of false then
        {System.printInfo "file terminated, returning "}
        {System.printInfo SUM}
        {System.printInfo "\n"}
        SUM
    elseof LINE then
        {System.printInfo "got "}
        {System.printInfo LINE}
        {System.printInfo "\n"}
        {SumLines FILE SUM+{String.toInt LINE}}
    end
end
    
in 
    local STDIN SUM in
        STDIN = {New TextFile init(name:stdin)}
        SUM = {SumLines STDIN 0}
        {System.printInfo SUM}
    end
    {Application.exit 0}
end
sumcol.parrot

        set I0, 0
AGAIN:
        readline S0, 0
        length I1, S0
        le I1, 0, MAINLOOP
        set I1, S0
        add I0, I1
        branch AGAIN

MAINLOOP:
        print I0
        print "\n"
        end
sumcol.perl
#!/usr/local/bin/perl
# $Id: sumcol.perl,v 1.4 2000/10/07 08:41:44 doug Exp $
# http://www.bagley.org/~doug/shootout/

use integer;
shift;
while (<>) { $tot += $_ }
print "$tot\n";
sumcol.php
#!/usr/local/bin/php -f<?php
/*
 $Id: sumcol.php,v 1.1 2001/05/13 04:19:17 doug Exp $
 http://www.bagley.org/~doug/shootout/
*/
$fd = fopen("php://stdin", "r");
$sum = 0;
while (!feof ($fd)) { $sum += fgets($fd, 1024); }
fclose($fd);
print "$sum\n";
?>
sumcol.pike
#!/usr/local/bin/pike// -*- mode: pike -*-
// $Id: sumcol.pike,v 1.7 2000/12/05 16:04:07 doug Exp $
// http://www.bagley.org/~doug/shootout/
// from: Fredrik Noring

void
main() {
    int sum = 0;
    while(string line = Stdio.stdin.gets())
    sum += (int)line;
    write("%d\n", sum);
}
sumcol.pliant
# $Id: sumcol.pliant,v 1.0 2002/02/08 12:07:00 dada Exp $
# http://dada.perl.it/shootout/

module "/pliant/language/context.pli"
module "/pliant/language/stream.pli"
module "/pliant/language/stream/pipe.pli"

gvar Str line := ""
(gvar Stream STDIN) open "handle:0" in
gvar uInt sum := 0
gvar Int i

while (STDIN atend) = false
  line := STDIN readline
  i := 0
  if(line parse i any)
    sum := sum + i

console sum eol
sumcol.poplisp
;;; -*- mode: lisp -*-
;;; $Id: sumcol.poplisp,v 1.0 2002/05/08 11:18:00 dada Exp $

  ;; fastest compilation mode 
  (declare (optimize (speed 3) (debug 0) (safety 0)))
  (let ((sum 0))
    (declare (fixnum sum))
    (do (
            (line 
                (read-line *standard-input* nil 'eof)
            )
        )
        (
            (eq line 'eof) (format t "~A~%" sum)
        )
        (incf sum (the fixnum (parse-integer line)))
    )
)
sumcol.python
#!/usr/local/bin/python
# $Id: sumcol.python,v 1.7 2001/05/09 00:45:50 doug Exp $
# http://www.bagley.org/~doug/shootout/
# with help from Mark Baker

import sys

def main():
    count = 0
    for line in sys.stdin.xreadlines():
        count += int(line)
    print count

main()
sumcol.rexx
NUMERIC FORM SCIENTIFIC
TOT = 0
DO WHILE LINES() <> 0
    PARSE LINEIN L
    IF L <> "" THEN DO
        INTERPRET "TOT = TOT + " L
    END
END
SAY TOT
sumcol.ruby
#!/usr/local/bin/ruby
# -*- mode: ruby -*-
# $Id: sumcol.ruby,v 1.4 2001/01/04 20:09:24 doug Exp $
# http://www.bagley.org/~doug/shootout/
# from: Mathieu Bouchard

count = 0
while STDIN.gets()
    count += $_.to_i
end
puts count
sumcol.se
-- -*- mode: eiffel -*-
-- $Id: sumcol.se,v 1.1 2000/10/12 07:11:43 doug Exp $
-- http://www.bagley.org/~doug/shootout/

class SUMCOL

creation make

feature

   make is

      local
     sum: INTEGER;
      do
     sum := 0
     from
        io.read_line
     until
        io.end_of_input
     loop
        sum := sum + io.last_string.to_integer
        io.read_line
     end
         std_output.put_integer(sum)
         std_output.put_character('%N')
      end
end
sumcol.slang
% $Id: sumcol.slang,v 1.0 2002/11/26 10:35:00 dada Exp $
% http://dada.perl.it/shootout/
%
% contributed by John E. Davis

define  main()
{
   variable count = 0;
   foreach (stdin) using ("line")
     {
    count += integer ();
     }
   vmessage ("%d", count);
}
main();
sumcol.smlnj
(* -*- mode: sml -*-
 * $Id: sumcol.smlnj,v 1.3 2001/07/09 00:25:28 doug Exp $
 * http://www.bagley.org/~doug/shootout/
 *)

structure Test : sig
    val main : (string * string list) -> OS.Process.status
end = struct

fun sumlines sum =
  if TextIO.endOfStream TextIO.stdIn
  then (print (Int.toString sum); print "\n")
  else case (Int.fromString (TextIO.inputLine TextIO.stdIn)) of
      NONE => sumlines sum
    | SOME i => sumlines (sum + i);

fun main(name, args) = (sumlines 0; OS.Process.success);

end

val _ = SMLofNJ.exportFn("sumcol", Test.main);
sumcol.tcl
#!/usr/local/bin/tclsh
# $Id: sumcol.tcl,v 1.5 2001/01/04 22:42:49 doug Exp $
# http://www.bagley.org/~doug/shootout/
# from: Miguel Sofer

proc main {} {
    set sum 0
    while {[gets stdin line]> 0} {
    incr sum $line
    }
    puts $sum
}

main
sumcol.vbscript
On Error Resume Next
tot = 0
Blob = WScript.StdIn.ReadAll
Nums = Split(Blob, Chr(10))
for each num in nums
    tot = tot + CInt(num)
Next
WScript.Echo(tot)
sumcol.vc
/* -*- mode: c -*-
 * $Id: sumcol.gcc,v 1.3 2000/12/24 05:43:53 doug Exp $
 * http://www.bagley.org/~doug/shootout/
 */

#include <stdio.h>
#include <stdlib.h>

#define MAXLINELEN 128

int
main() {
    int sum = 0;
    char line[MAXLINELEN];

    while (fgets(line, MAXLINELEN, stdin)) {
    sum += atoi(line);
    }
    printf("%d\n", sum);
    return(0);
}

sumcol.vc++
// -*- mode: c++ -*-
// $Id: sumcol.g++,v 1.4 2001/07/06 12:15:14 doug Exp $
// http://www.bagley.org/~doug/shootout/

#include <iostream>
#include <stdlib.h>

using namespace std;

#define MAXLINELEN 128

int main() {
    char line[MAXLINELEN];
    int sum = 0;
    ios_base::sync_with_stdio(false);
    cin.tie(0);

    while (cin.getline(line, MAXLINELEN)) {
        sum += atoi(line);
    }
    cout << sum << '\n';
}

sumcol.vpascal
program sumcol;

var
    num, tot: longint;
begin
    While Not Eof(input) Do
    begin
        ReadLn(input, num);    
        tot := tot + num;
    end;
    WriteLn(tot);
end.