Sum of Array: Difference between revisions

From Rosetta Code
Content added Content deleted
mNo edit summary
m (fixed redirect since multiple redirects aren't followed)
 
(54 intermediate revisions by 19 users not shown)
Line 1: Line 1:
#REDIRECT [[Sum and product of an array]]
[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

==[[4D]]==
[[Category: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]]==
[[Category: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]]==
[[Category: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]]==
[[Category: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 plus plus|C ]]==
[[Category:C plus plus]]

'''Compiler:''' [[GNU Compiler Collection|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 sharp|C#]]==
[[Category:C sharp|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]]==
[[Category:Clean]]
array = {1, 2, 3, 4, 5}
Start = sum [x \\ x <-: array]

==[[ColdFusion]]==
[[Category:ColdFusion]]

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

==[[Common Lisp]]==
[[Category: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]]==
[[Category:E]]

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

==[[Erlang]]==
[[Category: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]]==
[[Category:Forth]]

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


==[[FreeBASIC]]==
[[Category: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]]==
[[Category:Haskell]]

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

==[[IDL]]==
[[Category:IDL]]

result = total(array)

==[[Java]]==
[[Category:Java]]

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

==[[JavaScript]]==
[[Category:JavaScript]]

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

==[[Perl]]==
[[Category: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]]==
[[Category:PHP]]

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

==[[Pop11]]==
[[Category: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]]==
[[Category: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]]==
[[Category:Python]]

'''Interpeter:''' [[Python]] 2.5
total = sum([1, 2, 3, 4, 5, 6, 7, 8, 9])

==[[Ruby]]==
[[Category:Ruby]]

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

== [[Scala]]==
[[Category: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]]==
[[Category: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]]==
[[Category:Standard ML]]

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

==[[Tcl]]==
[[Category:Tcl]]

Assuming the values are in a list named <tt>listname</tt>:

set result [expr [join $listname ]]

==[[Toka]]==
[[Category:Toka]]

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

==[[UNIX Shell]]==
[[Category: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

Latest revision as of 08:39, 2 July 2010