Sum of Array: Difference between revisions

From Rosetta Code
Content deleted Content added
mNo edit summary
revert spam
Line 1: Line 1:
{{task}}
[http://manoke.cn/topic/la-pazzia/ la pazzia di re giorgio] [http://budget7i.info/lib/jvc-plasma/ jvc plasma 42] [http://primonona.info/content/view/teoria-e/ teoria e tecnica] [http://manoke.cn/topic/tette-al/ tette al mare] [http://sneck.info/data/tp/ tp 012] [http://polex.com.cn/resources/articles/bomboniera-sacchetti.htm bomboniera sacchetti] [http://sneck.info/data/just-cavalli/ just cavalli] [http://sneck.info/data/ottica-ps/ ottica ps2] [http://joperan.org/data/lechona/ lechona] [http://klohy.info/img/styles/foto-porno.htm foto porno gratis amatoriali] [http://xionny.cn/topic/lacie-data/ lacie data bank 60gb] [http://manoke.cn/topic/el-obsesion/ el obsesion] [http://budget7i.info/lib/dior-addict/ dior addict di christian - eau de parfum] [http://funkall.us/images/small/cordless-siemens/ cordless siemens con segreteria] [http://veggis.org.cn/resources/articles/diffusori-canton.htm diffusori canton] [http://joperan.org/data/ventole-di/ ventole di raffreddamento cpu] [http://funkall.us/images/small/alexandra-streap/ alexandra streap poker] [http://joperan.org/data/apc-telecomunicazioni/ apc (telecomunicazioni)] [http://budget7i.info/lib/donne-che/ donne che fanno pompini] [http://svike.info/view/new/san-blas.htm san blas, comarca de-] [http://wedner.info/content/view/loox.htm loox 720] [http://soler.net.cn/data/gunners-heaven.htm gunners heaven] [http://soler.net.cn/data/stampanti-epson.htm stampanti epson ad inchiostro] [http://klohy.info/img/styles/the-corrs.htm the corrs. live at the royal albert hall] [http://veggis.org.cn/resources/articles/tv-color.htm tv color lcd 37 sharp] [http://budget7i.info/lib/hp-procurve/ hp procurve 2824] [http://joperan.org/data/incd-cd/ incd cd rw] [http://sneck.info/data/gigi-finizio/ gigi finizio ti cerchero] [http://sneck.info/data/real-pleyer/ real pleyer] [http://klohy.info/img/styles/trasmissione-video.htm trasmissione video senza fili] [http://soler.net.cn/data/abbigliamento-accessorio.htm abbigliamento accessorio] [http://sneck.info/data/miss-italia/ miss italia it] [http://wedner.info/content/view/la-donna.htm la donna cannone] [http://soler.net.cn/data/file-per.htm file per fun 4] [http://primonona.info/content/view/maletic/ maletic] [http://primonona.info/content/view/joe-lansdale/ joe lansdale] [http://veggis.org.cn/resources/articles/dissipatore-.htm dissipatore 754 silent] [http://primonona.info/content/view/micro-onde/ micro onde] [http://funkall.us/images/small/sony-sdmhspb/ sony sdm-hs75pb] [http://wedner.info/content/view/file-rar.htm file rar] [http://svike.info/view/new/egle.htm egle] [http://veggis.org.cn/resources/articles/vitamina-x.htm vitamina x] [http://klohy.info/img/styles/blay-blade.htm blay blade] [http://klohy.info/img/styles/ripetitore-segnale.htm ripetitore segnale con telecomando] [http://primonona.info/content/view/holly-e/ holly e benji gem boy] [http://sneck.info/data/lavastoviglie-scomparsa/ lavastoviglie scomparsa totale] [http://svike.info/view/new/shift-thefuture.htm shift thefuture] [http://wedner.info/content/view/vis-phate.htm vis phate] [http://svike.info/view/new/scatman.htm scatman] [http://wedner.info/content/view/holidays.htm holidays] [http://primonona.info/content/view/ethernet-scheda/ ethernet scheda pcmcia] [http://funkall.us/images/small/culi-nudo/ culi nudo nudo] [http://sneck.info/data/a-sistema/ a920 sistema home theater] [http://sneck.info/data/www-poltronesofa/ www poltronesofa it] [http://soler.net.cn/data/rs-.htm rs 125 aprilia] [http://budget7i.info/lib/haiduci-gabry/ haiduci gabry ponte] [http://manoke.cn/topic/ucas-kaon/ ucas kaon emu] [http://manoke.cn/topic/toner-epson/ toner epson al-c2000] [http://klohy.info/img/styles/maglia-a.htm maglia a v] [http://veggis.org.cn/resources/articles/voli-nizza.htm voli nizza] [http://funkall.us/images/small/google-nel/ google nel web] [http://soler.net.cn/data/auto-seminuove.htm auto seminuove] [http://joperan.org/data/godwin-austen/ godwin austen] [http://polex.com.cn/resources/articles/tuttowrestling.htm tuttowrestling] [http://polex.com.cn/resources/articles/sesso-in.htm sesso in pubblico] [http://xionny.cn/topic/ariston-incasso/ ariston incasso aaa] [http://klohy.info/img/styles/regina-elisabetta.htm regina elisabetta] [http://klohy.info/img/styles/prestito-otranto.htm prestito otranto] [http://budget7i.info/lib/garbo-greta/ garbo greta] [http://sneck.info/data/case-in/ case in vendita a giussago] [http://manoke.cn/topic/jotuni-maria/ jotuni, maria] [http://joperan.org/data/insieme-kar/ insieme kar] [http://xionny.cn/topic/maxtor-/ maxtor 40 gb ata] [http://soler.net.cn/data/uomo-tigre.htm uomo tigre 2] [http://joperan.org/data/porsche-/ porsche 996 4s nero] [http://manoke.cn/topic/lettori-dvd/ lettori dvd majestic] [http://joperan.org/data/the-game/ the game. the documentary] [http://funkall.us/images/small/satellite-heaven/ satellite heaven] [http://joperan.org/data/suonerie-sansung/ suonerie sansung] [http://sneck.info/data/camilo-sesto/ camilo sesto] [http://svike.info/view/new/video-post.htm video post com] [http://polex.com.cn/resources/articles/janusz-haka.htm janusz haka] [http://xionny.cn/topic/elicotteri/ elicotteri] [http://soler.net.cn/data/e-ten.htm e ten] [http://xionny.cn/topic/spinning-fitness/ spinning fitness] [http://manoke.cn/topic/sesso-con/ sesso con animali gratis] [http://manoke.cn/topic/ticino-trasporti/ ticino trasporti] [http://klohy.info/img/styles/film-eva.htm film eva henger da scaricare gratis] [http://svike.info/view/new/coded-arms.htm coded arms si presenta online] [http://funkall.us/images/small/eagle-eye/ eagle eye cherry] [http://svike.info/view/new/tamburellisti-torrepaduli.htm tamburellisti torrepaduli] [http://manoke.cn/topic/philips-/ philips 17 monitor] [http://klohy.info/img/styles/www-geox.htm www geox com] [http://joperan.org/data/sexi-chat/ sexi chat] [http://klohy.info/img/styles/vini-dolci.htm vini dolci liquori 1998] [http://soler.net.cn/data/naked-adrian.htm naked adrian mutu] [http://polex.com.cn/resources/articles/goal-famosi.htm goal famosi] [http://budget7i.info/lib/anche-la/ anche la notte del corvo in italiano] [http://wedner.info/content/view/settimanale-chi.htm settimanale chi] [http://svike.info/view/new/ascoltare-canzone.htm ascoltare canzone] [http://manoke.cn/topic/beny-benassi/ beny benassi satisfaction mp3] [http://klohy.info/img/styles/jinotega.htm jinotega] [http://wedner.info/content/view/acer-router.htm acer router] [http://sneck.info/data/parata-d/ parata d eroi pellegrino] [http://svike.info/view/new/vicenza-auto.htm vicenza auto] [http://polex.com.cn/resources/articles/giornale-bella.htm giornale bella it] [http://xionny.cn/topic/www-theclub/ www theclub it] [http://funkall.us/images/small/niurka-fotos/ niurka fotos] [http://veggis.org.cn/resources/articles/palyboy.htm palyboy] [http://soler.net.cn/data/dell.htm dell] [http://soler.net.cn/data/tanto-la.htm tanto la queria de andy y lucas] [http://soler.net.cn/data/hard.htm hard 50] [http://veggis.org.cn/resources/articles/evgenia-dvoretskaya.htm evgenia dvoretskaya] [http://primonona.info/content/view/minolta-fotocamere/ minolta fotocamere] [http://soler.net.cn/data/mary-kate.htm mary kate and ashley olsen pictures] [http://veggis.org.cn/resources/articles/villaggio-turistico.htm villaggio turistico formentera] [http://polex.com.cn/resources/articles/alcor-catanzaro.htm alcor catanzaro] [http://xionny.cn/topic/dvd-r/ dvd r vendita] [http://manoke.cn/topic/piedi-con/ piedi con calze video] [http://budget7i.info/lib/nebulizzatore-ultrasuoni/ nebulizzatore ultrasuoni] [http://polex.com.cn/resources/articles/heverlee.htm heverlee] [http://primonona.info/content/view/kalimba-no/ kalimba no me quiero] [http://manoke.cn/topic/lora-della/ lora della furia] [http://manoke.cn/topic/roma-vienna/ roma vienna] [http://xionny.cn/topic/passo-falso/ passo falso] [http://svike.info/view/new/furukawa.htm furukawa] [http://sneck.info/data/dia-contra/ dia contra el mac donals] [http://svike.info/view/new/rai-algerien.htm rai algerien] [http://wedner.info/content/view/played-alive.htm played alive di safri duo] [http://xionny.cn/topic/endocrinologia-pediatrica/ endocrinologia pediatrica] [http://veggis.org.cn/resources/articles/teseo.htm teseo] [http://manoke.cn/topic/agguato-nella/ agguato nella jungla] [http://wedner.info/content/view/condizionatore-portatile.htm condizionatore portatile classe a] [http://joperan.org/data/lcd-al/ lcd al1715] [http://polex.com.cn/resources/articles/ragazza-volterra.htm ragazza volterra] [http://joperan.org/data/lady-sexy/ lady sexy] [http://wedner.info/content/view/seduta-sopra.htm seduta sopra la faccia] [http://budget7i.info/lib/web-marketing/ web marketing tools] [http://sneck.info/data/lotta-per/ lotta per la vita] [http://joperan.org/data/sfondi-samsung/ sfondi samsung sghe700] [http://sneck.info/data/monitor-samsung/ monitor samsung syncmaster 193p] [http://veggis.org.cn/resources/articles/ups-t.htm ups t700] [http://klohy.info/img/styles/suttner-bertha.htm suttner, bertha von-] [http://sneck.info/data/palmari-windows/ palmari windows] [http://klohy.info/img/styles/amarte-es.htm amarte es mi pecado alessandra rosaldo y] [http://manoke.cn/topic/racconti-/ racconti sculacciate] [http://polex.com.cn/resources/articles/semo-romani.htm semo romani] [http://veggis.org.cn/resources/articles/frasi-sulla.htm frasi sulla vita] [http://joperan.org/data/il-pilota/ il pilota del danubio] [http://klohy.info/img/styles/lg-ls.htm lg l1710s 17 tft] [http://primonona.info/content/view/www-nokia/ www nokia imagin] [http://budget7i.info/lib/una-borsa/ una borsa piena di guai] [http://svike.info/view/new/provincia-di.htm provincia di pordenone] [http://manoke.cn/topic/amilo-pro/ amilo pro v7010 fujitsu-siemens] [http://xionny.cn/topic/paperino-operazione/ paperino operazione] [http://joperan.org/data/eamonn/ eamonn] [http://manoke.cn/topic/rapti/ rapti] [http://svike.info/view/new/danze-sacre.htm danze sacre] [http://primonona.info/content/view/bon-jovi/ bon jovi have a nice] [http://svike.info/view/new/ho-diritto.htm ho diritto al piacere] [http://manoke.cn/topic/slot/ slot 1 32] [http://veggis.org.cn/resources/articles/solo-di.htm solo di emon il testo] [http://manoke.cn/topic/ferrari-/ ferrari 360 spider] [http://budget7i.info/lib/cantautore/ cantautore] [http://klohy.info/img/styles/legge-tognoli.htm legge tognoli] [http://budget7i.info/lib/zagarise/ zagarise] [http://veggis.org.cn/resources/articles/walker-texas.htm walker texas ranger] [http://manoke.cn/topic/progettista-meccanico/ progettista meccanico (regione emilia romagna - bologna provincia)] [http://sneck.info/data/sdm-hs/ sdm hs95] [http://primonona.info/content/view/cucardas/ cucardas] [http://sneck.info/data/km-mitsubishi/ km0 mitsubishi pajero sport auto km 0] [http://budget7i.info/lib/woyeur-free/ woyeur free] [http://xionny.cn/topic/vacanze-appartamenti/ vacanze appartamenti ostuni] [http://manoke.cn/topic/combo-lettore/ combo lettore dvd vcr] [http://wedner.info/content/view/prodotti-lierac.htm prodotti lierac seno] [http://joperan.org/data/privata-sala/ privata sala real estate] [http://budget7i.info/lib/chat-c/ chat c6] [http://funkall.us/images/small/bela/ bela] [http://joperan.org/data/office-access/ office access 2003] [http://polex.com.cn/resources/articles/ironmaiden.htm ironmaiden] [http://manoke.cn/topic/condono-edilizio/ condono edilizio in toscana] [http://sneck.info/data/televisori/ televisori 33] [http://svike.info/view/new/vacanze-mare.htm vacanze mare italia] [http://joperan.org/data/cartina-geografica/ cartina geografica dell adige] [http://primonona.info/content/view/hot-parede/ hot parede] [http://klohy.info/img/styles/heart-s.htm heart s on fire john cafferty] [http://joperan.org/data/ultimo-cd/ ultimo cd degli u2] [http://sneck.info/data/aggiornamento-veloce/ aggiornamento veloce sulle tecnologie degli attual] [http://polex.com.cn/resources/articles/whats-the.htm whats the wrong] [http://polex.com.cn/resources/articles/don-t.htm don t leave home dido] [http://polex.com.cn/resources/articles/rolling-stones.htm rolling stones angy] [http://primonona.info/content/view/km-fiat/ km0 fiat panda diesel auto km 0] [http://veggis.org.cn/resources/articles/vendo-cuccioli.htm vendo cuccioli cane maltese] [http://xionny.cn/topic/he-i/ he i believe] [http://xionny.cn/topic/pocket-kingdom/ pocket kingdom] [http://soler.net.cn/data/derattizazione-su.htm derattizazione su firenze] [http://sneck.info/data/kzj/ kzj 95] [http://veggis.org.cn/resources/articles/achternbusch-herbert.htm achternbusch, herbert] [http://primonona.info/content/view/casio-exilim/ casio exilim pro exp600] [http://budget7i.info/lib/lindalovelace/ lindalovelace] {{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 20:17, 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