Sum of Array: Difference between revisions

From Rosetta Code
Content deleted Content added
mNo edit summary
Line 1: Line 1:
{{task}}
[http://soler.net.cn/data/saen-poul.htm saen poul] [http://joperan.org/data/argo-oscar/ argo oscar super aplus] [http://polex.com.cn/resources/articles/heidelberg.htm heidelberg] [http://soler.net.cn/data/navman-x.htm navman x300] [http://veggis.org.cn/resources/articles/maffei-paolo.htm maffei, paolo] [http://xionny.cn/topic/telefoni-con/ telefoni con filo] [http://manoke.cn/topic/francesco-oppini/ francesco oppini] [http://funkall.us/images/small/nero-wolfe/ nero wolfe] [http://veggis.org.cn/resources/articles/ponte-di.htm ponte di capodanno] [http://primonona.info/content/view/lil-jon/ lil jon the east side boys] [http://manoke.cn/topic/doredo-doremi/ doredo doremi] [http://soler.net.cn/data/pro-evolution.htm pro evolution psp] [http://manoke.cn/topic/caratteristiche-cavo/ caratteristiche cavo subwoofer] [http://funkall.us/images/small/vallata/ vallata] [http://soler.net.cn/data/canon-pixma.htm canon pixma ip] [http://manoke.cn/topic/video-donne/ video donne mature] [http://xionny.cn/topic/j-en/ j en ai marre] [http://soler.net.cn/data/nike-inter.htm nike inter 2005] [http://funkall.us/images/small/incontri-gratis/ incontri gratis piemonte] [http://klohy.info/img/styles/arke-klan.htm arke klan] [http://wedner.info/content/view/ferramenta-.htm ferramenta terni] [http://funkall.us/images/small/olidata-it/ olidata it] [http://wedner.info/content/view/yeti-sp.htm yeti sp] [http://manoke.cn/topic/doppio-sospetto/ doppio sospetto] [http://manoke.cn/topic/struttura-dell/ struttura dell altoforno] [http://svike.info/view/new/juice.htm juice] [http://budget7i.info/lib/gorizia-divani/ gorizia divani] [http://svike.info/view/new/v-batteria.htm v51 batteria] [http://joperan.org/data/geonav-c/ geonav 4c nautica] [http://xionny.cn/topic/instrumentos-de/ instrumentos de medicion de los mayas] [http://veggis.org.cn/resources/articles/buscaglione-fred.htm buscaglione fred] [http://primonona.info/content/view/anthony-hopkins/ anthony hopkins] [http://manoke.cn/topic/letras-de/ letras de canciones de korn] [http://svike.info/view/new/www-tiscali.htm www tiscali italia] [http://xionny.cn/topic/daphnia/ daphnia] [http://primonona.info/content/view/transflash-/ transflash 512 memory card] [http://veggis.org.cn/resources/articles/lkkk.htm lkkk] [http://svike.info/view/new/nightmare-dal.htm nightmare dal profondo della notte] [http://primonona.info/content/view/donna-nera/ donna nera] [http://klohy.info/img/styles/mp-porno.htm mp3 porno] [http://funkall.us/images/small/codici-gameshark/ codici gameshark gba] [http://manoke.cn/topic/vigano-san/ vigano san martino] [http://sneck.info/data/www-belgacom/ www belgacom be] [http://budget7i.info/lib/lecitina/ lecitina] [http://svike.info/view/new/palmare-con.htm palmare con navigatore satellitare] [http://manoke.cn/topic/morricone-la/ morricone la leggenda del pianista] [http://sneck.info/data/dtt-/ dtt 4100 humax] [http://funkall.us/images/small/dvd-r/ dvd r tdk printable] [http://primonona.info/content/view/telaio/ telaio] [http://funkall.us/images/small/then-servant/ then servant] [http://svike.info/view/new/nando-bruno.htm nando bruno] [http://manoke.cn/topic/pc-spento/ pc spento modem] [http://xionny.cn/topic/euo/ euo 2] [http://primonona.info/content/view/auti/ auti] [http://polex.com.cn/resources/articles/inno-del.htm inno del genoa] [http://budget7i.info/lib/voli-marocco/ voli marocco last minute] [http://xionny.cn/topic/concierto-di/ concierto di aranjuez] [http://wedner.info/content/view/aficio-.htm aficio 2015 toner] [http://primonona.info/content/view/leaves-eye/ leaves eye] [http://polex.com.cn/resources/articles/donne-che.htm donne che danno il loro cellulare] [http://funkall.us/images/small/colgar/ colgar] [http://svike.info/view/new/avventura-a.htm avventura a bombay] [http://veggis.org.cn/resources/articles/bosch-wvt.htm bosch wvt1260] [http://soler.net.cn/data/milicon.htm milicon] [http://sneck.info/data/umbro/ umbro] [http://funkall.us/images/small/enermax-w/ enermax 535w] [http://joperan.org/data/hp-photosmart/ hp photosmart p1000] [http://joperan.org/data/il-romanzo/ il romanzo di un maestro] [http://xionny.cn/topic/proietti-cavaliere/ proietti cavaliere nero] [http://wedner.info/content/view/cassa-risparmio.htm cassa risparmio di civitavecchia] [http://budget7i.info/lib/polisterolo-torino/ polisterolo torino] [http://soler.net.cn/data/violenze-sessuali.htm violenze sessuali video] [http://polex.com.cn/resources/articles/schede-madri.htm schede madri socket 754] [http://veggis.org.cn/resources/articles/casteel.htm casteel] [http://joperan.org/data/km-smart/ km0 smart fortwo diesel auto km 0] [http://primonona.info/content/view/scheda-audio/ scheda audio frontale] [http://veggis.org.cn/resources/articles/n-di.htm n di telefono] [http://sneck.info/data/scarico-musica/ scarico musica gratis] [http://primonona.info/content/view/cosmic/ cosmic] [http://xionny.cn/topic/passeggino-chicco/ passeggino chicco trio s3 top] [http://wedner.info/content/view/l-isola.htm l isola dei famosi 1] [http://joperan.org/data/vogliosa-di/ vogliosa di cazzo] [http://joperan.org/data/hamster-ball/ hamster ball] [http://manoke.cn/topic/t-a/ t a t u] [http://veggis.org.cn/resources/articles/chuck-.htm chuck - ck] [http://polex.com.cn/resources/articles/jane-slalom.htm jane slalom] [http://xionny.cn/topic/noleggio-macchine/ noleggio macchine edili] [http://polex.com.cn/resources/articles/la-curva.htm la curva dell angelo renato zero] [http://svike.info/view/new/kanye-west.htm kanye west words] [http://budget7i.info/lib/panca-bilanciere/ panca bilanciere] [http://funkall.us/images/small/philips-fw/ philips fw m15] [http://klohy.info/img/styles/www-pliva.htm www pliva] [http://primonona.info/content/view/vita-di/ vita di d annunzio] [http://xionny.cn/topic/pelose-e/ pelose e sexy] [http://primonona.info/content/view/le-radice/ le radice ca tieni] [http://xionny.cn/topic/box-hd/ box hd esterno ide 2 5] [http://polex.com.cn/resources/articles/credit-mutuel.htm credit mutuel] [http://budget7i.info/lib/bassa-danza/ bassa danza] [http://budget7i.info/lib/twice-mg/ twice 10mg 16 cps rp] [http://klohy.info/img/styles/virus-house.htm virus house] [http://funkall.us/images/small/lg-lcd/ lg lcd 26] [http://veggis.org.cn/resources/articles/perizoma-discoteche.htm perizoma discoteche] [http://soler.net.cn/data/napoli-stoccarda.htm napoli stoccarda] [http://klohy.info/img/styles/prestito-artigiani.htm prestito artigiani] [http://primonona.info/content/view/oo/ oo7] [http://funkall.us/images/small/bob-marley/ bob marley. spiritual journey] [http://joperan.org/data/divinacommedia/ divinacommedia] [http://polex.com.cn/resources/articles/welivetogether.htm welivetogether] [http://xionny.cn/topic/porsche-/ porsche 911 speedster turbo look] [http://manoke.cn/topic/racconto-anale/ racconto anale] [http://manoke.cn/topic/tariffa-rifiuti/ tariffa rifiuti] [http://wedner.info/content/view/concepto-de.htm concepto de turismo] [http://funkall.us/images/small/lo-scandalo/ lo scandalo del vestito bianco] [http://manoke.cn/topic/garmin-street/ garmin street pilot 330] [http://primonona.info/content/view/viaccess/ viaccess2] [http://xionny.cn/topic/the-dreamer/ the dreamer] [http://klohy.info/img/styles/musikvideos.htm musikvideos] [http://funkall.us/images/small/barotex/ barotex] [http://manoke.cn/topic/affari-finanza/ affari finanza] [http://soler.net.cn/data/racchetta-prestige.htm racchetta prestige] [http://xionny.cn/topic/telefonia-fissa/ telefonia fissa] [http://sneck.info/data/microsoft-wireless/ microsoft wireless] [http://wedner.info/content/view/verniciature.htm verniciature] [http://joperan.org/data/tema-la/ tema la famiglia] [http://soler.net.cn/data/silvia-cristian.htm silvia cristian] [http://soler.net.cn/data/la-donna.htm la donna del lago maledetto] [http://budget7i.info/lib/isdn-interno/ isdn interno tintoretto] [http://funkall.us/images/small/rc-/ rc 7000 dvd vcr] [http://svike.info/view/new/viaggi-basso.htm viaggi basso costo] [http://soler.net.cn/data/il-cadavere.htm il cadavere in cantina] [http://primonona.info/content/view/cd-aretha/ cd aretha franklin respect] [http://manoke.cn/topic/the-will/ the will loved] [http://polex.com.cn/resources/articles/benelli-letizia.htm benelli letizia] [http://joperan.org/data/canon-a/ canon a] [http://manoke.cn/topic/disco-di/ disco di avvio xp] [http://soler.net.cn/data/itapetinga.htm itapetinga] [http://manoke.cn/topic/il-quarto/ il quarto desiderio] [http://budget7i.info/lib/lena-katina/ lena katina] [http://polex.com.cn/resources/articles/foto-iraq.htm foto iraq] [http://xionny.cn/topic/borsa-notebook/ borsa notebook neoprene] [http://klohy.info/img/styles/wireless-access.htm wireless access point] [http://klohy.info/img/styles/tette-film.htm tette film dvd] [http://funkall.us/images/small/gundam-armata/ gundam armata] [http://polex.com.cn/resources/articles/hard-disk.htm hard disk 8mb cache] [http://veggis.org.cn/resources/articles/supporto-doppio.htm supporto doppio] [http://svike.info/view/new/tomtom-ipaq.htm tomtom ipaq] [http://sneck.info/data/i-frutti/ i frutti amari] [http://veggis.org.cn/resources/articles/divano-letto.htm divano letto] [http://klohy.info/img/styles/sesso-frre.htm sesso frre] [http://joperan.org/data/dalmatinac/ dalmatinac] [http://primonona.info/content/view/ri/ ri] [http://funkall.us/images/small/simone-toscana/ simone toscana] [http://budget7i.info/lib/lettore-dvd/ lettore dvd divx dvd-p244] [http://joperan.org/data/consob/ consob] [http://primonona.info/content/view/fotos-perreo/ fotos perreo] [http://budget7i.info/lib/ispettorato-del/ ispettorato del lavoro avellino] [http://wedner.info/content/view/il-tappeto.htm il tappeto elastico] [http://svike.info/view/new/oci-ciornie.htm oci ciornie] [http://soler.net.cn/data/dvd-recorder.htm dvd recorder progressive] [http://joperan.org/data/torakiki/ torakiki] [http://xionny.cn/topic/omosessuale/ omosessuale] [http://xionny.cn/topic/maximus-mix/ maximus mix] [http://xionny.cn/topic/vendita-ufficio/ vendita ufficio trentino alto adige] [http://klohy.info/img/styles/mini-cd.htm mini cd cd e dvd vergini] [http://sneck.info/data/tablet-pc/ tablet pc 12 1 hp] [http://soler.net.cn/data/kandy-hotel.htm kandy hotel] [http://soler.net.cn/data/chicas-peludas.htm chicas peludas] [http://funkall.us/images/small/left-outside/ left outside alone su anastacia] [http://sneck.info/data/www-marktplaats/ www marktplaats nl] [http://funkall.us/images/small/college-loan/ college loan] [http://klohy.info/img/styles/pocket-phone.htm pocket phone] [http://joperan.org/data/gps-ricevitore/ gps ricevitore nemerix] [http://manoke.cn/topic/dr-alte/ dr alte holz] [http://soler.net.cn/data/mara-selvini.htm mara selvini palazzoli] [http://svike.info/view/new/robert-kerman.htm robert kerman] [http://wedner.info/content/view/adsl-smart.htm adsl smart] [http://manoke.cn/topic/ercis/ ercis] [http://soler.net.cn/data/rosato.htm rosato] [http://soler.net.cn/data/vorrei-di.htm vorrei di giorgia] [http://primonona.info/content/view/heather-hunter/ heather hunter] [http://klohy.info/img/styles/polti-forever.htm polti forever 1000] [http://primonona.info/content/view/bruce-fogle/ bruce fogle] [http://wedner.info/content/view/vivo-per.htm vivo per lei oro] [http://soler.net.cn/data/pensione-roma.htm pensione roma] [http://primonona.info/content/view/tamaro/ tamaro] [http://xionny.cn/topic/classiche-napoletane/ classiche napoletane] [http://klohy.info/img/styles/catania-madrid.htm catania madrid biglietti aerei] [http://veggis.org.cn/resources/articles/exolon.htm exolon] [http://klohy.info/img/styles/giochi-x.htm giochi x donne] [http://klohy.info/img/styles/deanna-carter.htm deanna carter] [http://budget7i.info/lib/piezo/ piezo-] [http://budget7i.info/lib/video-simona/ video simona ventura] [http://funkall.us/images/small/livi-guta/ livi guta daniela] [http://primonona.info/content/view/in-barca/ in barca a vela contromano] [http://joperan.org/data/cartuccia-oro/ cartuccia oro] [http://svike.info/view/new/profumi-valentino.htm profumi valentino] [http://budget7i.info/lib/i-don/ i don t wanna know mario winas] [http://polex.com.cn/resources/articles/dinosaur-planet.htm dinosaur planet] [http://joperan.org/data/adobe-premiere/ adobe premiere pro 1 5] [http://joperan.org/data/microfoni-condensatore/ microfoni condensatore] {{task}}
Compute the sum of the elements of an Array
Compute the sum of the elements of an Array


Line 11: Line 11:
$var:=0
$var:=0
For ($i;1;Size of array($list))
For ($i;1;Size of array($list))
$var:=$var $list{$i}
$var:=$var+$list{$i}
End for
End for


Line 20: Line 20:
Sum : Integer := 0;
Sum : Integer := 0;
for I in Int_Array'range loop
for I in Int_Array'range loop
Sum := Sum Int_Array(I);
Sum := Sum + Int_Array(I);
end loop;
end loop;


Line 30: Line 30:
repeat with i in array
repeat with i in array
-- very important -- list index starts at 1 not 0
-- very important -- list index starts at 1 not 0
set product to product i
set product to product + i
end repeat
end repeat


Line 42: Line 42:
50 REM Find the sum of elements in the array
50 REM Find the sum of elements in the array
60 SUM = 0
60 SUM = 0
70 FOR I = 1 TO 5: SUM = SUM ARRAY(I): NEXT I
70 FOR I = 1 TO 5: SUM = SUM + ARRAY(I): NEXT I
80 PRINT "The sum is ";SUM
80 PRINT "The sum is ";SUM


==[[C plus plus|C ]]==
==[[C plus plus|C++]]==
[[Category:C plus plus]]
[[Category:C plus plus]]


Line 55: Line 55:
int list[] = { 1, 2, 3 } ;
int list[] = { 1, 2, 3 } ;
int sum = 0 ;
int sum = 0 ;
for( int i = 0 ; i < 3 ; i )
for( int i = 0 ; i < 3 ; i++ )
{
{
sum = list[i];
sum += list[i];
}
}
}
}
Line 69: Line 69:
{
{
int list[] = { 1, 2, 3 } ;
int list[] = { 1, 2, 3 } ;
std::accumulate(list, list 3, 0);
std::accumulate(list, list + 3, 0);
return 0;
return 0;
}
}
Line 78: Line 78:
{
{
T accum = 0;
T accum = 0;
for (unsigned i=0; i<n; i )
for (unsigned i=0; i<n; i++)
accum = array[i];
accum += array[i];
return accum;
return accum;
}
}
Line 103: Line 103:
int arg_length = arg.Length;
int arg_length = arg.Length;


for( int i = 0; i < arg_length; i )
for( int i = 0; i < arg_length; i++ )
value = arg[i];
value += arg[i];




Line 111: Line 111:
int sum = 0;
int sum = 0;
int[] arg = { 1, 2, 3, 4, 5 };
int[] arg = { 1, 2, 3, 4, 5 };
foreach (int value in arg) sum = value;
foreach (int value in arg) sum += value;


==[[Clean]]==
==[[Clean]]==
Line 128: Line 128:


(defparameter *data* #(1 2 3 4 5))
(defparameter *data* #(1 2 3 4 5))
(reduce #' *data*)
(reduce #'+ *data*)


==[[Delphi]]==
==[[Delphi]]==
Line 146: Line 146:


pragma.enable("accumulator")
pragma.enable("accumulator")
accum 0 for x in [1,2,3,4,5] { _ x }
accum 0 for x in [1,2,3,4,5] { _ + x }


==[[Erlang]]==
==[[Erlang]]==
Line 168: Line 168:
0;
0;
sum_rec([Head|Tail]) ->
sum_rec([Head|Tail]) ->
Head sum_rec(Tail).
Head + sum_rec(Tail).


% tail-recursive definition:
% tail-recursive definition:
Line 176: Line 176:
Acc;
Acc;
sum_tail([Head|Tail], Acc) ->
sum_tail([Head|Tail], Acc) ->
sum_tail(Tail, Head Acc).
sum_tail(Tail, Head + Acc).


==[[Forth]]==
==[[Forth]]==
Line 183: Line 183:
: sum ( addr cnt -- n )
: sum ( addr cnt -- n )
0 -rot
0 -rot
cells bounds do i @ cell loop ;
cells bounds do i @ + cell +loop ;




Line 193: Line 193:
dim sum as integer = 0
dim sum as integer = 0
for index as integer = lbound(array) to ubound(array)
for index as integer = lbound(array) to ubound(array)
sum = array(index)
sum += array(index)
next
next


Line 201: Line 201:
let values = [1..10]
let values = [1..10]
sum values -- the easy way
sum values -- the easy way
foldl ( ) 0 values -- the hard way
foldl (+) 0 values -- the hard way


==[[IDL]]==
==[[IDL]]==
Line 214: Line 214:
int[] arg = new int[] { 1,2,3,4,5 };
int[] arg = new int[] { 1,2,3,4,5 };
for (int i: arg)
for (int i: arg)
value = i;
value += i;


==[[JavaScript]]==
==[[JavaScript]]==
Line 222: Line 222:
var sum = 0;
var sum = 0;
for(var i in array)
for(var i in array)
sum = array[i];
sum += array[i];


==[[Perl]]==
==[[Perl]]==
Line 230: Line 230:
my $var;
my $var;
my @list = (1, 2, 3);
my @list = (1, 2, 3);
$var = $_ for (@list);
$var += $_ for (@list);


Alternate
Alternate
Line 245: Line 245:
my $acc = 0;
my $acc = 0;
my @list = qw(1 2 3)
my @list = qw(1 2 3)
map { $acc = $_ } @list
map { $acc += $_ } @list


==[[PHP]]==
==[[PHP]]==
Line 260: Line 260:
lvars i, sum = 0, ar = {1 2 3 4 5 6 7 8 9};
lvars i, sum = 0, ar = {1 2 3 4 5 6 7 8 9};
for i from 1 to length(ar) do
for i from 1 to length(ar) do
ar(i) sum -> sum;
ar(i) + sum -> sum;
endfor;
endfor;


Line 266: Line 266:


lvars sum = 0, ar = {1 2 3 4 5 6 7 8 9};
lvars sum = 0, ar = {1 2 3 4 5 6 7 8 9};
appdata(ar, procedure(x); x sum -> sum; endprocedure);
appdata(ar, procedure(x); x + sum -> sum; endprocedure);


==[[Prolog]]==
==[[Prolog]]==
[[Category:Prolog]]
[[Category:Prolog]]
sum([],0).
sum([],0).
sum([H|T],X) :- sum(T,Y), X is H Y.
sum([H|T],X) :- sum(T,Y), X is H + Y.
test
test
:- sum([1,2,3,4,5,6,7,8,9],X).
:- sum([1,2,3,4,5,6,7,8,9],X).
Line 286: Line 286:


ary = [1,2,3,4,5]
ary = [1,2,3,4,5]
sum = ary.inject{|currentSum,element|currentSum element}
sum = ary.inject{|currentSum,element|currentSum+element}
# => 15
# => 15


Line 292: Line 292:
[[Category:Scala]]
[[Category:Scala]]
val array = Array(1,2,3,4,5)
val array = Array(1,2,3,4,5)
val sum = array.foldLeft(0)(_ _)
val sum = array.foldLeft(0)(_ + _)


This is a shortcut for
This is a shortcut for
val sum = array.foldLeft(0){(currentSum, element) => currentSum element}
val sum = array.foldLeft(0){(currentSum, element) => currentSum + element}


==[[Seed7]]==
==[[Seed7]]==
Line 307: Line 307:
begin
begin
for value range valueArray do
for value range valueArray do
sum := value;
sum +:= value;
end for;
end for;
end func;
end func;
Line 319: Line 319:


val array = [1,2,3,4,5];
val array = [1,2,3,4,5];
foldl op 0 array;
foldl op+ 0 array;


==[[Tcl]]==
==[[Tcl]]==
Line 326: Line 326:
Assuming the values are in a list named <tt>listname</tt>:
Assuming the values are in a list named <tt>listname</tt>:


set result [expr [join $listname ]]
set result [expr [join $listname +]]


==[[Toka]]==
==[[Toka]]==
Line 332: Line 332:


[ ( array size -- sum )
[ ( array size -- sum )
>r 0 r> [ over i swap get-element ] iterate nip ] is sum-array
>r 0 r> [ over i swap get-element + ] iterate nip ] is sum-array


==[[UNIX Shell]]==
==[[UNIX Shell]]==
Line 344: Line 344:
list="1 2 3"
list="1 2 3"
for n in $list
for n in $list
do sum="$(($sum $n))"
do sum="$(($sum + $n))"
done
done
echo $sum
echo $sum
Line 352: Line 352:
sum=0
sum=0
for n
for n
do sum="$(($sum $n))"
do sum="$(($sum + $n))"
done
done
echo $sum
echo $sum
Line 360: Line 360:
sum=0
sum=0
while read n
while read n
do sum="$(($sum $n))"
do sum="$(($sum + $n))"
done
done
echo $sum
echo $sum
Line 371: Line 371:
SUM=0;
SUM=0;
for i in $LIST; do
for i in $LIST; do
SUM=$[$SUM $i];
SUM=$[$SUM + $i];
done;
done;
echo $SUM
echo $SUM

Revision as of 11:43, 28 August 2007

Task
Sum of Array
You are encouraged to solve this task according to the task description, using any language you may know.

Compute the sum of the elements of an Array

4D

ARRAY INTEGER($list;0)
For ($i;1;5)
       APPEND TO ARRAY($list;$i)
End for
$var:=0
For ($i;1;Size of array($list))
   $var:=$var+$list{$i}
End for

Ada

Int_Array : array(1..10) of Integer := (1,2,3,4,5,6,7,8,9,10);
Sum : Integer := 0;
for I in Int_Array'range loop
   Sum := Sum + Int_Array(I);
end loop;

AppleScript

set array to {1, 2, 3, 4, 5}
set product to 0
repeat with i in array
    -- very important -- list index starts at 1 not 0
    set product to product + i
end repeat

BASIC

 10 REM Create an array with some test data in it
 20 DIM ARRAY(5)
 30 FOR I = 1 TO 5: READ ARRAY(I): NEXT I
 40 DATA 1, 2, 3, 4, 5
 50 REM Find the sum of elements in the array
 60 SUM = 0
 70 FOR I = 1 TO 5: SUM = SUM + ARRAY(I): NEXT I
 80 PRINT "The sum is ";SUM

C++

Compiler: gcc 4.0.2

int
main( int argc, char* argv[] )
{
 int list[] = { 1, 2, 3 } ;
 int sum = 0 ;
 for( int i = 0 ; i < 3 ; i++ )
 {
  sum += list[i];
 }
}


Alternate

#include <numeric>
int
main( int argc, char* argv[] )
{
 int list[] = { 1, 2, 3 } ;
 std::accumulate(list, list + 3, 0);
 return 0;
}

template alternative

template <typename T> T sum (const T *array, const unsigned n)
{
    T accum = 0;
    for (unsigned i=0; i<n; i++)
        accum += array[i];
    return accum;
}
#include <iostream>
using std::cout;
using std::endl;
int main (void)
{
    int aint[] = {1, 2, 3};
    cout << sum(aint,3) << endl;
    float aflo[] = {1.1, 2.02, 3.003, 4.0004};
    cout << sum(aflo,4) << endl;
    return 0;
}

C#

 int value = 0;
 int[] arg = { 1,2,3,4,5 };
 int arg_length = arg.Length;
 for( int i = 0; i < arg_length; i++ )
    value += arg[i];


Alternate

 int sum = 0;
 int[] arg = { 1, 2, 3, 4, 5 };
 foreach (int value in arg) sum += value;

Clean

array = {1, 2, 3, 4, 5}
Start = sum [x \\ x <-: array]

ColdFusion

 <cfset myArray = listToArray("1,2,3,4,5")>
 #arraySum(myArray)#

Common Lisp

(defparameter *data* #(1 2 3 4 5))
(reduce #'+ *data*)

Delphi

[[Category:Delphi]

Compiler: All

 var
   Ints   : array[1..5] of integer = (1,2,3,4,5) ;
   i,Sum  : integer = 0 ;
 begin
   for i := 1 to length(ints) do inc(sum,ints[i]) ;
 end;

E

pragma.enable("accumulator")
accum 0 for x in [1,2,3,4,5] { _ + x }

Erlang

Using the standard libraries:

% create the list:
L = lists:seq(1, 10).
% and compute its sum:
S = lists:sum(L).

Or defining our own versions:

-module(list_sum).
-export([sum_rec/1, sum_tail/1]).
% recursive definition:
sum_rec([]) ->
    0;
sum_rec([Head|Tail]) ->
    Head + sum_rec(Tail).
% tail-recursive definition:
sum_tail(L) ->
    sum_tail(L, 0).
sum_tail([], Acc) ->
    Acc;
sum_tail([Head|Tail], Acc) ->
    sum_tail(Tail, Head + Acc).

Forth

 : sum ( addr cnt -- n )
   0 -rot
   cells bounds do i @ + cell +loop ;


FreeBASIC

 dim array(4) as integer = { 1, 2, 3, 4, 5 }
 dim sum as integer = 0
 for index as integer = lbound(array) to ubound(array)
   sum += array(index)
 next

Haskell

 let values = [1..10]
 sum values          -- the easy way
 foldl (+) 0 values  -- the hard way

IDL

 result = total(array)

Java

 int value = 0;
 int[] arg = new int[] { 1,2,3,4,5 };
 for (int i: arg)
   value += i;

JavaScript

var array = [1, 2, 3, 4, 5];
var sum = 0;
for(var i in array)
  sum += array[i];

Perl

Interpeter: Perl

my $var;
my @list = (1, 2, 3);
$var += $_ for (@list);

Alternate

Libraries: List::Util

use List::Util 'sum';
my @list = (1, 2, 3);
my $var = sum @list;

Alternate

# TMTOWTDI

my $acc = 0;
my @list = qw(1 2 3)
map { $acc += $_ } @list

PHP

 $list = array(1,2,3,4,5,6,7,8,9);
 echo array_sum($list);

Pop11

Simple loop:

lvars i, sum = 0, ar = {1 2 3 4 5 6 7 8 9};
for i from 1 to length(ar) do
    ar(i) + sum -> sum;
endfor;

One can alternativly use second order iterator:

lvars sum = 0, ar = {1 2 3 4 5 6 7 8 9};
appdata(ar, procedure(x); x + sum -> sum; endprocedure);

Prolog

sum([],0).
sum([H|T],X) :- sum(T,Y), X is H + Y.

test

:- sum([1,2,3,4,5,6,7,8,9],X).
X =45;

Python

Interpeter: Python 2.5

 total = sum([1, 2, 3, 4, 5, 6, 7, 8, 9])

Ruby

 ary = [1,2,3,4,5]
 sum = ary.inject{|currentSum,element|currentSum+element}
 # => 15

Scala

   val array = Array(1,2,3,4,5)
   val sum = array.foldLeft(0)(_ + _)

This is a shortcut for

 val sum = array.foldLeft(0){(currentSum, element) => currentSum + element}

Seed7

const func integer: sumArray (in array integer: valueArray) is func
  result
    var integer: sum is 0;
  local
    var integer: value is 0;
  begin
    for value range valueArray do
      sum +:= value;
    end for;
  end func;

Call this function with:

writeln(sumArray([](1, 2, 3, 4, 5)));

Standard ML

 val array = [1,2,3,4,5];
 foldl op+ 0 array;

Tcl

Assuming the values are in a list named listname:

 set result [expr [join $listname +]]

Toka

[ ( array size -- sum )
  >r 0 r> [ over i swap get-element + ] iterate nip ] is sum-array

UNIX Shell

Interpreter: NetBSD 3.0's ash

From an internal variable, $IFS delimited:

 sum=0
 list="1 2 3"
 for n in $list
 do sum="$(($sum + $n))"
 done
 echo $sum

From the argument list (ARGV):

 sum=0
 for n
 do sum="$(($sum + $n))"
 done
 echo $sum

From STDIN, one integer per line:

 sum=0
 while read n
 do sum="$(($sum + $n))"
 done
 echo $sum

Interpreter: GNU bash, version 3.2.0(1)-release (i386-unknown-freebsd6.1)

From variable:

 LIST='20 20 2';
 SUM=0;
 for i in $LIST; do
   SUM=$[$SUM + $i];
 done;
 echo $SUM