Sum and product of an array: Difference between revisions
Langurmonkey (talk | contribs) |
|||
(179 intermediate revisions by 94 users not shown) | |||
Line 1: | Line 1: | ||
{{task|Arithmetic operations}} |
{{task|Arithmetic operations}} |
||
[[Category:Iteration]] |
|||
;Task: |
|||
Compute the sum and product of an array of integers. |
Compute the sum and product of an array of integers. |
||
<br><br> |
|||
=={{header|11l}}== |
|||
<syntaxhighlight lang="11l">V arr = [1, 2, 3, 4] |
|||
print(sum(arr)) |
|||
print(product(arr))</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
10 |
|||
24 |
|||
</pre> |
|||
=={{header|360 Assembly}}== |
|||
<syntaxhighlight lang="360asm">* Sum and product of an array 20/04/2017 |
|||
SUMPROD CSECT |
|||
USING SUMPROD,R15 base register |
|||
SR R3,R3 su=0 |
|||
LA R5,1 pr=1 |
|||
LA R6,1 i=1 |
|||
DO WHILE=(CH,R6,LE,=AL2((PG-A)/4)) do i=1 to hbound(a) |
|||
LR R1,R6 i |
|||
SLA R1,2 *4 |
|||
A R3,A-4(R1) su=su+a(i) |
|||
M R4,A-4(R1) pr=pr*a(i) |
|||
LA R6,1(R6) i++ |
|||
ENDDO , enddo i |
|||
XDECO R3,PG su |
|||
XDECO R5,PG+12 pr |
|||
XPRNT PG,L'PG print |
|||
BR R14 exit |
|||
A DC F'1',F'2',F'3',F'4',F'5',F'6',F'7',F'8',F'9',F'10' |
|||
PG DS CL24 buffer |
|||
YREGS |
|||
END SUMPROD</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
55 3628800 |
|||
</pre> |
|||
=={{header|4D}}== |
=={{header|4D}}== |
||
< |
<syntaxhighlight lang="4d">ARRAY INTEGER($list;0) |
||
For ($i;1;5) |
For ($i;1;5) |
||
APPEND TO ARRAY($list;$i) |
APPEND TO ARRAY($list;$i) |
||
Line 12: | Line 55: | ||
$sum:=$var+$list{$i} |
$sum:=$var+$list{$i} |
||
$product:=$product*$list{$i} |
$product:=$product*$list{$i} |
||
End for |
End for |
||
// since 4D v13 |
|||
$sum:=sum($list) |
|||
</syntaxhighlight> |
|||
=={{header|AArch64 Assembly}}== |
|||
{{works with|as|Raspberry Pi 3B version Buster 64 bits <br> or android 64 bits with application Termux }} |
|||
<syntaxhighlight lang AArch64 Assembly> |
|||
/* ARM assembly AARCH64 Raspberry PI 3B */ |
|||
/* program sumandproduct64.s */ |
|||
/************************************/ |
|||
/* Constantes */ |
|||
/************************************/ |
|||
/* for this file see task include a file in language AArch64 assembly*/ |
|||
.include "../includeConstantesARM64.inc" |
|||
/*********************************/ |
|||
/* Initialized data */ |
|||
/*********************************/ |
|||
.data |
|||
szMessSum: .asciz "Sum = " |
|||
szMessProd: .asciz "Product = " |
|||
szMessStart: .asciz "Program 64 bits start.\n" |
|||
szCarriageReturn: .asciz "\n" |
|||
szMessErreur: .asciz "Overflow ! \n" |
|||
tabArray: .quad 2, 11, 19, 90, 55,1000000 |
|||
.equ TABARRAYSIZE, (. - tabArray) / 8 |
|||
/*********************************/ |
|||
/* UnInitialized data */ |
|||
/*********************************/ |
|||
.bss |
|||
sZoneConv: .skip 24 |
|||
/*********************************/ |
|||
/* code section */ |
|||
/*********************************/ |
|||
.text |
|||
.global main |
|||
main: // entry of program |
|||
ldr x0,qAdrszMessStart |
|||
bl affichageMess |
|||
ldr x2,qAdrtabArray |
|||
mov x1,#0 // indice |
|||
mov x0,#0 // sum init |
|||
1: |
|||
ldr x3,[x2,x1,lsl #3] |
|||
adds x0,x0,x3 |
|||
bcs 99f |
|||
add x1,x1,#1 |
|||
cmp x1,#TABARRAYSIZE |
|||
blt 1b |
|||
ldr x1,qAdrsZoneConv |
|||
bl conversion10 // decimal conversion |
|||
mov x0,#3 // number string to display |
|||
ldr x1,qAdrszMessSum |
|||
ldr x2,qAdrsZoneConv // insert conversion in message |
|||
ldr x3,qAdrszCarriageReturn |
|||
bl displayStrings // display message |
|||
ldr x2,qAdrtabArray |
|||
mov x1,#0 // indice |
|||
mov x0,#1 // product init |
|||
2: |
|||
ldr x3,[x2,x1,lsl #3] |
|||
mul x0,x3,x0 |
|||
umulh x4,x3,x0 |
|||
cmp x4,#0 |
|||
bne 99f |
|||
add x1,x1,#1 |
|||
cmp x1,#TABARRAYSIZE |
|||
blt 2b |
|||
ldr x1,qAdrsZoneConv |
|||
bl conversion10 // decimal conversion |
|||
mov x0,#3 // number string to display |
|||
ldr x1,qAdrszMessProd |
|||
ldr x2,qAdrsZoneConv // insert conversion in message |
|||
ldr x3,qAdrszCarriageReturn |
|||
bl displayStrings // display message |
|||
b 100f |
|||
99: |
|||
ldr x0,qAdrszMessErreur |
|||
bl affichageMess |
|||
100: // standard end of the program |
|||
mov x0, #0 // return code |
|||
mov x8,EXIT |
|||
svc #0 // perform the system call |
|||
qAdrszCarriageReturn: .quad szCarriageReturn |
|||
qAdrsZoneConv: .quad sZoneConv |
|||
qAdrszMessSum: .quad szMessSum |
|||
qAdrszMessProd: .quad szMessProd |
|||
qAdrszMessErreur: .quad szMessErreur |
|||
qAdrszMessStart: .quad szMessStart |
|||
qAdrtabArray: .quad tabArray |
|||
/***************************************************/ |
|||
/* display multi strings */ |
|||
/* new version 24/05/2023 */ |
|||
/***************************************************/ |
|||
/* x0 contains number strings address */ |
|||
/* x1 address string1 */ |
|||
/* x2 address string2 */ |
|||
/* x3 address string3 */ |
|||
/* x4 address string4 */ |
|||
/* x5 address string5 */ |
|||
/* x6 address string5 */ |
|||
displayStrings: // INFO: displayStrings |
|||
stp x7,lr,[sp,-16]! // save registers |
|||
stp x2,fp,[sp,-16]! // save registers |
|||
add fp,sp,#32 // save paraméters address (4 registers saved * 8 bytes) |
|||
mov x7,x0 // save strings number |
|||
cmp x7,#0 // 0 string -> end |
|||
ble 100f |
|||
mov x0,x1 // string 1 |
|||
bl affichageMess |
|||
cmp x7,#1 // number > 1 |
|||
ble 100f |
|||
mov x0,x2 |
|||
bl affichageMess |
|||
cmp x7,#2 |
|||
ble 100f |
|||
mov x0,x3 |
|||
bl affichageMess |
|||
cmp x7,#3 |
|||
ble 100f |
|||
mov x0,x4 |
|||
bl affichageMess |
|||
cmp x7,#4 |
|||
ble 100f |
|||
mov x0,x5 |
|||
bl affichageMess |
|||
cmp x7,#5 |
|||
ble 100f |
|||
mov x0,x6 |
|||
bl affichageMess |
|||
100: |
|||
ldp x2,fp,[sp],16 // restaur registers |
|||
ldp x7,lr,[sp],16 // restaur registers |
|||
ret |
|||
/***************************************************/ |
|||
/* ROUTINES INCLUDE */ |
|||
/***************************************************/ |
|||
/* for this file see task include a file in language AArch64 assembly*/ |
|||
.include "../includeARM64.inc" |
|||
</syntaxhighlight> |
|||
{{Out}} |
|||
<pre> |
|||
Program 64 bits start. |
|||
Sum = 1000177 |
|||
Product = 2069100000000 |
|||
</pre> |
|||
=={{header|ACL2}}== |
=={{header|ACL2}}== |
||
< |
<syntaxhighlight lang="lisp">(defun sum (xs) |
||
(if (endp xs) |
(if (endp xs) |
||
0 |
0 |
||
Line 25: | Line 222: | ||
1 |
1 |
||
(* (first xs) |
(* (first xs) |
||
(prod (rest xs)))))</ |
(prod (rest xs)))))</syntaxhighlight> |
||
=={{header|Action!}}== |
|||
<syntaxhighlight lang="action!">DEFINE LAST="6" |
|||
PROC Main() |
|||
INT ARRAY data=[1 2 3 4 5 6 7] |
|||
BYTE i |
|||
INT a,res |
|||
res=0 |
|||
FOR i=0 TO LAST |
|||
DO |
|||
a=data(i) |
|||
PrintI(a) |
|||
IF i=LAST THEN |
|||
Put('=) |
|||
ELSE |
|||
Put('+) |
|||
FI |
|||
res==+a |
|||
OD |
|||
PrintIE(res) |
|||
res=1 |
|||
FOR i=0 TO LAST |
|||
DO |
|||
a=data(i) |
|||
PrintI(a) |
|||
IF i=LAST THEN |
|||
Put('=) |
|||
ELSE |
|||
Put('*) |
|||
FI |
|||
res=res*a |
|||
OD |
|||
PrintIE(res) |
|||
RETURN</syntaxhighlight> |
|||
{{out}} |
|||
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Sum_and_product_of_an_array.png Screenshot from Atari 8-bit computer] |
|||
<pre> |
|||
1+2+3+4+5+6+7=28 |
|||
1*2*3*4*5*6*7=5040 |
|||
</pre> |
|||
=={{header|ActionScript}}== |
=={{header|ActionScript}}== |
||
< |
<syntaxhighlight lang="actionscript">package { |
||
import flash.display.Sprite; |
import flash.display.Sprite; |
||
Line 49: | Line 289: | ||
} |
} |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Ada}}== |
=={{header|Ada}}== |
||
< |
<syntaxhighlight lang="ada">type Int_Array is array(Integer range <>) of Integer; |
||
array : Int_Array := (1,2,3,4,5,6,7,8,9,10); |
array : Int_Array := (1,2,3,4,5,6,7,8,9,10); |
||
Line 58: | Line 298: | ||
for I in array'range loop |
for I in array'range loop |
||
Sum := Sum + array(I); |
Sum := Sum + array(I); |
||
end loop;</ |
end loop;</syntaxhighlight> |
||
Define the product function |
Define the product function |
||
< |
<syntaxhighlight lang="ada">function Product(Item : Int_Array) return Integer is |
||
Prod : Integer := 1; |
Prod : Integer := 1; |
||
begin |
begin |
||
Line 67: | Line 307: | ||
end loop; |
end loop; |
||
return Prod; |
return Prod; |
||
end Product;</ |
end Product;</syntaxhighlight> |
||
This function will raise the predefined exception Constraint_Error if the product overflows the values represented by type Integer |
This function will raise the predefined exception Constraint_Error if the product overflows the values represented by type Integer |
||
=={{header|Aime}}== |
|||
<syntaxhighlight lang="aime">void |
|||
compute(integer &s, integer &p, list l) |
|||
{ |
|||
integer v; |
|||
s = 0; |
|||
p = 1; |
|||
for (, v in l) { |
|||
s += v; |
|||
p *= v; |
|||
} |
|||
} |
|||
integer |
|||
main(void) |
|||
{ |
|||
integer sum, product; |
|||
compute(sum, product, list(2, 3, 5, 7, 11, 13, 17, 19)); |
|||
o_form("~\n~\n", sum, product); |
|||
return 0; |
|||
}</syntaxhighlight> |
|||
{{out}} |
|||
<pre>77 |
|||
9699690</pre> |
|||
=={{header|ALGOL 68}}== |
=={{header|ALGOL 68}}== |
||
< |
<syntaxhighlight lang="algol68">main:( |
||
INT default upb := 3; |
INT default upb := 3; |
||
MODE INTARRAY = [default upb]INT; |
MODE INTARRAY = [default upb]INT; |
||
Line 90: | Line 360: | ||
) # int product # ; |
) # int product # ; |
||
printf(($" Sum: "g(0)$,sum,$", Product:"g(0)";"l$,int product(array))) |
printf(($" Sum: "g(0)$,sum,$", Product:"g(0)";"l$,int product(array))) |
||
)</ |
)</syntaxhighlight> |
||
{{Out}} |
|||
Output: |
|||
<pre> |
|||
Sum: 55, Product:3628800; |
Sum: 55, Product:3628800; |
||
</pre> |
|||
=={{header| |
=={{header|ALGOL W}}== |
||
<syntaxhighlight lang="algolw">begin |
|||
<lang aime>void |
|||
compute(integer &s, integer &p, list l) |
|||
{ |
|||
integer i; |
|||
% computes the sum and product of intArray % |
|||
s = 0; |
|||
% the results are returned in sum and product % |
|||
p = 1; |
|||
% the bounds of the array must be specified in lb and ub % |
|||
i = l_length(l); |
|||
procedure sumAndProduct( integer array intArray ( * ) |
|||
while (i) { |
|||
; integer value lb, ub |
|||
; integer result sum, product |
|||
s += l_q_integer(l, i); |
|||
) ; |
|||
begin |
|||
} |
|||
sum := 0; |
|||
integer |
|||
product := 1; |
|||
main(void) |
|||
{ |
|||
integer sum, product; |
|||
for i := lb until ub |
|||
compute(sum, product, l_effect(2, 3, 5, 7, 11, 13, 17, 19)); |
|||
do begin |
|||
sum := sum + intArray( i ); |
|||
product := product * intArray( i ); |
|||
end for_i ; |
|||
end sumAndProduct ; |
|||
o_newline(); |
|||
% test the sumAndProduct procedure % |
|||
o_integer(product); |
|||
begin |
|||
integer array v ( 1 :: 10 ); |
|||
integer sum, product; |
|||
for i := 1 until 10 do v( i ) := i; |
|||
sumAndProduct( v, 1, 10, sum, product ); |
|||
write( sum, product ); |
|||
end |
|||
end.</syntaxhighlight> |
|||
return 0; |
|||
}</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
55 3628800 |
|||
9699690</pre> |
|||
</pre> |
|||
=={{header|APL}}== |
=={{header|APL}}== |
||
{{works with|APL2}} |
{{works with|APL2}} |
||
< |
<syntaxhighlight lang="apl"> sum ← +/ ⍝ sum (+) over (/) an array |
||
prod ← ×/ |
prod ← ×/ ⍝ product (×) over (/) an array |
||
a ← 1 2 3 4 5 ⍝ assign a literal array to variable 'a' |
|||
sum |
sum a ⍝ or simply: +/a |
||
15 |
15 |
||
prod |
prod a ⍝ or simply: ×/a |
||
120</ |
120</syntaxhighlight> |
||
What follows ⍝ is a comment and / is usually known as ''reduce'' in APL. The use of the ''sum'' and ''prod'' functions is not necessary and was added only to please people baffled by the extreme conciseness of using APL symbols. |
|||
{{works with|dzaima/APL}} ([https://tio.run/##SyzI0U2pSszMTfz//1Hf1EdtEzS09R/1rjs8XV/TUMFIwVjBRMH0/38A Try It Online]) |
|||
{{works with|Extended Dyalog APL}} ([https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn//1HfVIVHbRMUNLT1FR71rlM4PF1fU8FQwUjBWMFEwfT/fwA Try It Online]) |
|||
using the [https://aplwiki.com/wiki/Pair pair (⍮)] primitive function |
|||
<syntaxhighlight lang="apl"> ⎕ ← (+/ ⍮ ×/) 1 2 3 4 5 |
|||
15 120</syntaxhighlight> |
|||
Spaces are optional except as separators between array elements. |
|||
=={{header|AppleScript}}== |
=={{header|AppleScript}}== |
||
< |
<syntaxhighlight lang="applescript">set array to {1, 2, 3, 4, 5} |
||
set sum to 0 |
set sum to 0 |
||
set product to 1 |
set product to 1 |
||
Line 147: | Line 436: | ||
set sum to sum + i |
set sum to sum + i |
||
set product to product * i |
set product to product * i |
||
end repeat</ |
end repeat</syntaxhighlight> |
||
Condensed version of above, which also prints the results : |
|||
<syntaxhighlight lang="applescript"> |
|||
set {array, sum, product} to {{1, 2, 3, 4, 5}, 0, 1} |
|||
repeat with i in array |
|||
set {sum, product} to {sum + i, product * i} |
|||
end repeat |
|||
return sum & " , " & product as string |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
"15 , 120" |
|||
</pre> |
|||
Or, using an AppleScript implementation of '''fold'''/'''reduce''': |
|||
<syntaxhighlight lang="applescript">on summed(a, b) |
|||
a + b |
|||
end summed |
|||
on product(a, b) |
|||
a * b |
|||
end product |
|||
-- TEST ----------------------------------------------------------------------- |
|||
on run |
|||
set xs to enumFromTo(1, 10) |
|||
{xs, ¬ |
|||
{sum:foldl(summed, 0, xs)}, ¬ |
|||
{product:foldl(product, 1, xs)}} |
|||
--> {{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, {sum:55}, {product:3628800}} |
|||
end run |
|||
-- GENERIC FUNCTIONS ---------------------------------------------------------- |
|||
-- enumFromTo :: Int -> Int -> [Int] |
|||
on enumFromTo(m, n) |
|||
if n < m then |
|||
set d to -1 |
|||
else |
|||
set d to 1 |
|||
end if |
|||
set lst to {} |
|||
repeat with i from m to n by d |
|||
set end of lst to i |
|||
end repeat |
|||
return lst |
|||
end enumFromTo |
|||
-- foldl :: (a -> b -> a) -> a -> [b] -> a |
|||
on foldl(f, startValue, xs) |
|||
tell mReturn(f) |
|||
set v to startValue |
|||
set lng to length of xs |
|||
repeat with i from 1 to lng |
|||
set v to |λ|(v, item i of xs, i, xs) |
|||
end repeat |
|||
return v |
|||
end tell |
|||
end foldl |
|||
-- Lift 2nd class handler function into 1st class script wrapper |
|||
-- mReturn :: Handler -> Script |
|||
on mReturn(f) |
|||
if class of f is script then |
|||
f |
|||
else |
|||
script |
|||
property |λ| : f |
|||
end script |
|||
end if |
|||
end mReturn</syntaxhighlight> |
|||
{{Out}} |
|||
<syntaxhighlight lang="applescript">{{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, {sum:55}, {product:3628800}}</syntaxhighlight> |
|||
=={{header|ARM Assembly}}== |
|||
{{works with|as|Raspberry Pi <br> or android 32 bits with application Termux}} |
|||
<syntaxhighlight lang ARM Assembly> |
|||
/* ARM assembly Raspberry PI */ |
|||
/* program sumandproduct.s */ |
|||
/* REMARK 1 : this program use routines in a include file |
|||
see task Include a file language arm assembly |
|||
for the routine affichageMess conversion10 |
|||
see at end of this program the instruction include */ |
|||
/* for constantes see task include a file in arm assembly */ |
|||
/************************************/ |
|||
/* Constantes */ |
|||
/************************************/ |
|||
.include "../constantes.inc" |
|||
/*********************************/ |
|||
/* Initialized data */ |
|||
/*********************************/ |
|||
.data |
|||
szMessSum: .asciz "Sum = " |
|||
szMessProd: .asciz "Product = " |
|||
szMessStart: .asciz "Program 32 bits start.\n" |
|||
szCarriageReturn: .asciz "\n" |
|||
szMessErreur: .asciz "Overflow ! \n" |
|||
tabArray: .int 2, 11, 19, 90, 55,1000 |
|||
.equ TABARRAYSIZE, (. - tabArray) / 4 |
|||
/*********************************/ |
|||
/* UnInitialized data */ |
|||
/*********************************/ |
|||
.bss |
|||
sZoneConv: .skip 24 |
|||
/*********************************/ |
|||
/* code section */ |
|||
/*********************************/ |
|||
.text |
|||
.global main |
|||
main: @ entry of program |
|||
ldr r0,iAdrszMessStart |
|||
bl affichageMess |
|||
ldr r2,iAdrtabArray |
|||
mov r1,#0 @ indice |
|||
mov r0,#0 @ sum init |
|||
1: |
|||
ldr r3,[r2,r1,lsl #2] |
|||
adds r0,r0,r3 |
|||
bcs 99f |
|||
add r1,r1,#1 |
|||
cmp r1,#TABARRAYSIZE |
|||
blt 1b |
|||
ldr r1,iAdrsZoneConv |
|||
bl conversion10 @ decimal conversion |
|||
mov r3,#0 |
|||
strb r3,[r1,r0] |
|||
mov r0,#3 @ number string to display |
|||
ldr r1,iAdrszMessSum |
|||
ldr r2,iAdrsZoneConv @ insert conversion in message |
|||
ldr r3,iAdrszCarriageReturn |
|||
bl displayStrings @ display message |
|||
ldr r2,iAdrtabArray |
|||
mov r1,#0 @ indice |
|||
mov r0,#1 @ product init |
|||
2: |
|||
ldr r3,[r2,r1,lsl #2] |
|||
umull r0,r4,r3,r0 |
|||
cmp r4,#0 |
|||
bne 99f |
|||
add r1,r1,#1 |
|||
cmp r1,#TABARRAYSIZE |
|||
blt 2b |
|||
ldr r1,iAdrsZoneConv |
|||
bl conversion10 @ decimal conversion |
|||
mov r3,#0 |
|||
strb r3,[r1,r0] |
|||
mov r0,#3 @ number string to display |
|||
ldr r1,iAdrszMessProd |
|||
ldr r2,iAdrsZoneConv @ insert conversion in message |
|||
ldr r3,iAdrszCarriageReturn |
|||
bl displayStrings @ display message |
|||
b 100f |
|||
99: |
|||
ldr r0,iAdrszMessErreur |
|||
bl affichageMess |
|||
100: @ standard end of the program |
|||
mov r0, #0 @ return code |
|||
mov r7, #EXIT @ request to exit program |
|||
svc #0 @ perform the system call |
|||
iAdrszCarriageReturn: .int szCarriageReturn |
|||
iAdrsZoneConv: .int sZoneConv |
|||
iAdrszMessSum: .int szMessSum |
|||
iAdrszMessProd: .int szMessProd |
|||
iAdrszMessErreur: .int szMessErreur |
|||
iAdrszMessStart: .int szMessStart |
|||
iAdrtabArray: .int tabArray |
|||
/***************************************************/ |
|||
/* display multi strings */ |
|||
/***************************************************/ |
|||
/* r0 contains number strings address */ |
|||
/* r1 address string1 */ |
|||
/* r2 address string2 */ |
|||
/* r3 address string3 */ |
|||
/* other address on the stack */ |
|||
/* thinck to add number other address * 4 to add to the stack */ |
|||
displayStrings: @ INFO: displayStrings |
|||
push {r1-r4,fp,lr} @ save des registres |
|||
add fp,sp,#24 @ save paraméters address (6 registers saved * 4 bytes) |
|||
mov r4,r0 @ save strings number |
|||
cmp r4,#0 @ 0 string -> end |
|||
ble 100f |
|||
mov r0,r1 @ string 1 |
|||
bl affichageMess |
|||
cmp r4,#1 @ number > 1 |
|||
ble 100f |
|||
mov r0,r2 |
|||
bl affichageMess |
|||
cmp r4,#2 |
|||
ble 100f |
|||
mov r0,r3 |
|||
bl affichageMess |
|||
cmp r4,#3 |
|||
ble 100f |
|||
mov r3,#3 |
|||
sub r2,r4,#4 |
|||
1: @ loop extract address string on stack |
|||
ldr r0,[fp,r2,lsl #2] |
|||
bl affichageMess |
|||
subs r2,#1 |
|||
bge 1b |
|||
100: |
|||
pop {r1-r4,fp,pc} |
|||
/***************************************************/ |
|||
/* ROUTINES INCLUDE */ |
|||
/***************************************************/ |
|||
.include "../affichage.inc" |
|||
</syntaxhighlight> |
|||
{{Out}} |
|||
<pre> |
|||
Program 32 bits start. |
|||
Sum = 1177 |
|||
Product = 2069100000 |
|||
</pre> |
|||
=={{header|Arturo}}== |
|||
<syntaxhighlight lang="rebol">arr: 1..10 |
|||
print ["Sum =" sum arr] |
|||
print ["Product =" product arr]</syntaxhighlight> |
|||
{{out}} |
|||
<pre>Sum = 55 |
|||
Product = 3628800</pre> |
|||
=={{header|Asymptote}}== |
|||
<syntaxhighlight lang="asymptote">int[] matriz = {1,2,3,4,5}; |
|||
int suma = 0, prod = 1; |
|||
for (int p : matriz) { |
|||
suma += p; |
|||
prod *= p; |
|||
} |
|||
write("Sum = ", suma); |
|||
write("Product = ", prod);</syntaxhighlight> |
|||
{{out}} |
|||
<pre>Sum = 15 |
|||
Product = 120</pre> |
|||
=={{header|AutoHotkey}}== |
=={{header|AutoHotkey}}== |
||
< |
<syntaxhighlight lang="autohotkey">numbers = 1,2,3,4,5 |
||
product := 1 |
product := 1 |
||
loop, parse, numbers, `, |
loop, parse, numbers, `, |
||
Line 156: | Line 698: | ||
product *= A_LoopField |
product *= A_LoopField |
||
} |
} |
||
msgbox, sum = %sum%`nproduct = %product%</ |
msgbox, sum = %sum%`nproduct = %product%</syntaxhighlight> |
||
=={{header|AWK}}== |
=={{header|AWK}}== |
||
For array input, it is easiest to "deserialize" it from a string with the split() function. |
For array input, it is easiest to "deserialize" it from a string with the split() function. |
||
< |
<syntaxhighlight lang="awk">$ awk 'func sum(s){split(s,a);r=0;for(i in a)r+=a[i];return r}{print sum($0)}' |
||
1 2 3 4 5 6 7 8 9 10 |
1 2 3 4 5 6 7 8 9 10 |
||
55 |
55 |
||
Line 165: | Line 708: | ||
$ awk 'func prod(s){split(s,a);r=1;for(i in a)r*=a[i];return r}{print prod($0)}' |
$ awk 'func prod(s){split(s,a);r=1;for(i in a)r*=a[i];return r}{print prod($0)}' |
||
1 2 3 4 5 6 7 8 9 10 |
1 2 3 4 5 6 7 8 9 10 |
||
3628800</ |
3628800</syntaxhighlight> |
||
=={{header|Babel}}== |
=={{header|Babel}}== |
||
< |
<syntaxhighlight lang="babel">main: { [2 3 5 7 11 13] sp } |
||
sum! : { <- 0 -> { + } eachar } |
sum! : { <- 0 -> { + } eachar } |
||
Line 180: | Line 723: | ||
Result: |
Result: |
||
41 |
41 |
||
30030</ |
30030</syntaxhighlight> |
||
Perhaps better Babel: |
Perhaps better Babel: |
||
< |
<syntaxhighlight lang="babel">main: |
||
{ [2 3 5 7 11 13] |
{ [2 3 5 7 11 13] |
||
ar2ls dup cp |
ar2ls dup cp |
||
Line 202: | Line 745: | ||
{ * } |
{ * } |
||
{ depth 1 > } |
{ depth 1 > } |
||
do_while } nest }</ |
do_while } nest }</syntaxhighlight> |
||
The nest operator creates a kind of argument-passing context - |
The nest operator creates a kind of argument-passing context - |
||
Line 215: | Line 758: | ||
=={{header|BASIC}}== |
=={{header|BASIC}}== |
||
{{works with|FreeBASIC}} |
{{works with|FreeBASIC}} |
||
< |
<syntaxhighlight lang="freebasic">dim array(5) as integer = { 1, 2, 3, 4, 5 } |
||
dim sum as integer = 0 |
dim sum as integer = 0 |
||
Line 222: | Line 765: | ||
sum += array(index) |
sum += array(index) |
||
prod *= array(index) |
prod *= array(index) |
||
next</ |
next</syntaxhighlight> |
||
==={{header|Applesoft BASIC}}=== |
==={{header|Applesoft BASIC}}=== |
||
{{works with|Commodore BASIC}} |
|||
<lang ApplesoftBasic> 10 N = 5 |
|||
<syntaxhighlight lang="applesoftbasic"> 10 N = 5 |
|||
20 S = 0:P = 1: DATA 1,2,3,4,5 |
20 S = 0:P = 1: DATA 1,2,3,4,5 |
||
30 N = N - 1: DIM A(N) |
30 N = N - 1: DIM A(N) |
||
40 |
40 FOR I = 0 TO N |
||
50 |
50 READ A(I): NEXT |
||
60 |
60 FOR I = 0 TO N |
||
70 S = S + A(I):P = P * A(I) |
70 S = S + A(I):P = P * A(I) |
||
80 |
80 NEXT |
||
90 |
90 PRINT "SUM="S,"PRODUCT="P</syntaxhighlight> |
||
=={{header| |
==={{header|Atari BASIC}}=== |
||
Almost the same code works in Atari BASIC, but you can't READ directly into arrays, leave the variable off a NEXT, or concatenate values in PRINT without semicolons between them: |
|||
<lang bbcbasic> DIM array%(5) |
|||
<syntaxhighlight lang="basic">10 N = 5 |
|||
20 S = 0:P = 1: DATA 1,2,3,4,5 |
|||
30 N = N - 1: DIM A(N) |
|||
40 FOR I = 0 TO N |
|||
50 READ X:A(I) = X: NEXT I |
|||
60 FOR I = 0 TO N |
|||
70 S = S + A(I):P = P * A(I) |
|||
80 NEXT I |
|||
90 PRINT "SUM=";S,"PRODUCT=";P</syntaxhighlight> |
|||
==={{header|BaCon}}=== |
|||
<syntaxhighlight lang="freebasic"> |
|||
'--- set some values into the array |
|||
DECLARE a[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10 } TYPE int |
|||
sum = 0 |
|||
product = 1 |
|||
i = 1 |
|||
WHILE a[i] <= 10 |
|||
sum = sum + a[i] |
|||
product = product * a[i] |
|||
INCR i |
|||
WEND |
|||
PRINT "The sum is ",sum |
|||
PRINT "The product is ",product |
|||
</syntaxhighlight> |
|||
==={{header|Chipmunk Basic}}=== |
|||
{{works with|Chipmunk Basic|3.6.4}} |
|||
{{works with|QBasic}} |
|||
<syntaxhighlight lang="qbasic">10 rem Sum and product of an array |
|||
20 dim array(4)' array de 5 eltos. |
|||
30 data 1,2,3,4,5 |
|||
40 for index = 0 to ubound(array) |
|||
50 read array(index) |
|||
60 next index |
|||
70 sum = 0 |
|||
80 prod = 1 |
|||
90 for index = 0 to 4 ubound(array) |
|||
100 sum = sum+array(index) |
|||
110 prod = prod*array(index) |
|||
120 next index |
|||
130 print "The sum is ";sum |
|||
140 print "and the product is ";prod |
|||
150 end</syntaxhighlight> |
|||
==={{header|BBC BASIC}}=== |
|||
<syntaxhighlight lang="bbcbasic"> DIM array%(5) |
|||
array%() = 1, 2, 3, 4, 5, 6 |
array%() = 1, 2, 3, 4, 5, 6 |
||
Line 245: | Line 840: | ||
product% *= array%(I%) |
product% *= array%(I%) |
||
NEXT |
NEXT |
||
PRINT "Product of array elements = " ; product%</ |
PRINT "Product of array elements = " ; product%</syntaxhighlight> |
||
==={{header|IS-BASIC}}=== |
|||
<syntaxhighlight lang="is-basic">100 RANDOMIZE |
|||
110 LET N=5 |
|||
120 NUMERIC A(1 TO N) |
|||
130 LET SUM=0:LET PROD=1 |
|||
140 FOR I=1 TO N |
|||
150 LET A(I)=RND(9)+1 |
|||
160 PRINT A(I); |
|||
170 NEXT |
|||
180 PRINT |
|||
190 FOR I=1 TO N |
|||
200 LET SUM=SUM+A(I):LET PROD=PROD*A(I) |
|||
210 NEXT |
|||
220 PRINT "Sum =";SUM,"Product =";PROD</syntaxhighlight> |
|||
=={{header|BASIC256}}== |
|||
{{trans|Yabasic}} |
|||
<syntaxhighlight lang="basic256">arraybase 1 |
|||
dim array(5) |
|||
array[1] = 1 |
|||
array[2] = 2 |
|||
array[3] = 3 |
|||
array[4] = 4 |
|||
array[5] = 5 |
|||
sum = 0 |
|||
prod = 1 |
|||
for index = 1 to array[?] |
|||
sum += array[index] |
|||
prod *= array[index] |
|||
next index |
|||
print "The sum is "; sum #15 |
|||
print "and the product is "; prod #120 |
|||
end</syntaxhighlight> |
|||
=={{header|bc}}== |
=={{header|bc}}== |
||
< |
<syntaxhighlight lang="bc">a[0] = 3.0 |
||
a[1] = 1 |
a[1] = 1 |
||
a[2] = 4.0 |
a[2] = 4.0 |
||
Line 261: | Line 893: | ||
} |
} |
||
"Sum: "; s |
"Sum: "; s |
||
"Product: "; p</ |
"Product: "; p</syntaxhighlight> |
||
=={{header|Befunge}}== |
=={{header|Befunge}}== |
||
{{works with|befungee}} |
{{works with|befungee}} |
||
The program first reads the number of elements in the array, then the elements themselves (each number on a separate line) and calculates their sum. |
The program first reads the number of elements in the array, then the elements themselves (each number on a separate line) and calculates their sum. |
||
< |
<syntaxhighlight lang="befunge">0 &>: #v_ $. @ |
||
>1- \ & + \v |
>1- \ & + \v |
||
^ <</ |
^ <</syntaxhighlight> |
||
=={{header|BQN}}== |
|||
Getting the sum and product as a two element array fits nicely within a tacit fork pattern. |
|||
* Sum <code>+´</code> |
|||
* Paired with <code>⋈</code> |
|||
* Product <code>×´</code> |
|||
<syntaxhighlight lang="bqn"> SumProd ← +´⋈×´ |
|||
+´⋈×´ |
|||
SumProd 1‿2‿3‿4‿5 |
|||
⟨ 15 120 ⟩</syntaxhighlight> |
|||
=={{header|Bracmat}}== |
=={{header|Bracmat}}== |
||
< |
<syntaxhighlight lang="bracmat">( ( sumprod |
||
= sum prod num |
= sum prod num |
||
. 0:?sum |
. 0:?sum |
||
Line 286: | Line 931: | ||
) |
) |
||
& out$sumprod$(2 3 5 7 11 13 17 19) |
& out$sumprod$(2 3 5 7 11 13 17 19) |
||
);</ |
);</syntaxhighlight> |
||
{{Out}} |
|||
Output: |
|||
<pre>77.9699690</pre> |
<pre>77.9699690</pre> |
||
=={{header|Bruijn}}== |
|||
<syntaxhighlight lang="bruijn"> |
|||
:import std/List . |
|||
:import std/Math . |
|||
arr (+1) : ((+2) : ((+3) : {}(+4))) |
|||
main [∑arr : ∏arr] |
|||
</syntaxhighlight> |
|||
=={{header|C}}== |
=={{header|C}}== |
||
< |
<syntaxhighlight lang="c">/* using pointer arithmetic (because we can, I guess) */ |
||
int arg[] = { 1,2,3,4,5 }; |
int arg[] = { 1,2,3,4,5 }; |
||
int arg_length = sizeof(arg)/sizeof(arg[0]); |
int arg_length = sizeof(arg)/sizeof(arg[0]); |
||
Line 301: | Line 956: | ||
sum += *p; |
sum += *p; |
||
prod *= *p; |
prod *= *p; |
||
}</ |
}</syntaxhighlight> |
||
=={{header|C sharp|C#}}== |
|||
<syntaxhighlight lang="csharp">int sum = 0, prod = 1; |
|||
int[] arg = { 1, 2, 3, 4, 5 }; |
|||
foreach (int value in arg) { |
|||
sum += value; |
|||
prod *= value; |
|||
}</syntaxhighlight> |
|||
===Alternative using Linq (C# 3)=== |
|||
{{works with|C sharp|C#|3}} |
|||
<syntaxhighlight lang="csharp">int[] arg = { 1, 2, 3, 4, 5 }; |
|||
int sum = arg.Sum(); |
|||
int prod = arg.Aggregate((runningProduct, nextFactor) => runningProduct * nextFactor);</syntaxhighlight> |
|||
=={{header|C++}}== |
=={{header|C++}}== |
||
{{libheader|STL}} |
{{libheader|STL}} |
||
< |
<syntaxhighlight lang="cpp">#include <numeric> |
||
#include <functional> |
#include <functional> |
||
Line 312: | Line 983: | ||
// std::accumulate(arg, arg + 5, 0); |
// std::accumulate(arg, arg + 5, 0); |
||
// since plus() is the default functor for accumulate |
// since plus() is the default functor for accumulate |
||
int prod = std::accumulate(arg, arg+5, 1, std::multiplies<int>());</ |
int prod = std::accumulate(arg, arg+5, 1, std::multiplies<int>());</syntaxhighlight> |
||
Template alternative: |
Template alternative: |
||
< |
<syntaxhighlight lang="cpp">// this would be more elegant using STL collections |
||
template <typename T> T sum (const T *array, const unsigned n) |
template <typename T> T sum (const T *array, const unsigned n) |
||
{ |
{ |
||
Line 341: | Line 1,012: | ||
cout << sum(aflo,4) << " " << prod(aflo,4) << endl; |
cout << sum(aflo,4) << " " << prod(aflo,4) << endl; |
||
return 0; |
return 0; |
||
}</ |
}</syntaxhighlight> |
||
=={{header|C sharp|C#}}== |
|||
<lang csharp>int sum = 0, prod = 1; |
|||
int[] arg = { 1, 2, 3, 4, 5 }; |
|||
foreach (int value in arg) { |
|||
sum += value; |
|||
prod *= value; |
|||
}</lang> |
|||
===Alternative using Linq (C# 3)=== |
|||
{{works with|C sharp|C#|3}} |
|||
<lang csharp>int[] arg = { 1, 2, 3, 4, 5 }; |
|||
int sum = arg.Sum(); |
|||
int prod = arg.Aggregate((runningProduct, nextFactor) => runningProduct * nextFactor);</lang> |
|||
=={{header|Chef}}== |
=={{header|Chef}}== |
||
< |
<syntaxhighlight lang="chef">Sum and Product of Numbers as a Piece of Cake. |
||
This recipe sums N given numbers. |
This recipe sums N given numbers. |
||
Line 381: | Line 1,038: | ||
Pour contents of 1st mixing bowl into the baking dish. |
Pour contents of 1st mixing bowl into the baking dish. |
||
Serves 1.</ |
Serves 1.</syntaxhighlight> |
||
=={{header|Clean}}== |
=={{header|Clean}}== |
||
< |
<syntaxhighlight lang="clean">array = {1, 2, 3, 4, 5} |
||
Sum = sum [x \\ x <-: array] |
Sum = sum [x \\ x <-: array] |
||
Prod = foldl (*) 1 [x \\ x <-: array]</ |
Prod = foldl (*) 1 [x \\ x <-: array]</syntaxhighlight> |
||
=={{header|Clojure}}== |
=={{header|Clojure}}== |
||
< |
<syntaxhighlight lang="lisp">(defn sum [vals] (reduce + vals)) |
||
(defn product [vals] (reduce * vals))</ |
(defn product [vals] (reduce * vals))</syntaxhighlight> |
||
=={{header|CLU}}== |
|||
<syntaxhighlight lang="clu">sum_and_product = proc (a: array[int]) returns (int,int) signals (overflow) |
|||
sum: int := 0 |
|||
prod: int := 1 |
|||
for i: int in array[int]$elements(a) do |
|||
sum := sum + i |
|||
prod := prod * i |
|||
end resignal overflow |
|||
return(sum, prod) |
|||
end sum_and_product |
|||
start_up = proc () |
|||
arr: array[int] := array[int]$[1,2,3,4,5,6,7,8,9,10] |
|||
sum, prod: int := sum_and_product(arr) |
|||
po: stream := stream$primary_output() |
|||
stream$putl(po, "Sum = " || int$unparse(sum)) |
|||
stream$putl(po, "Product = " || int$unparse(prod)) |
|||
end start_up</syntaxhighlight> |
|||
{{out}} |
|||
<pre>Sum = 55 |
|||
Product = 3628800</pre> |
|||
=={{header|COBOL}}== |
=={{header|COBOL}}== |
||
< |
<syntaxhighlight lang="cobol"> IDENTIFICATION DIVISION. |
||
PROGRAM-ID. array-sum-and-product. |
PROGRAM-ID. array-sum-and-product. |
||
Line 419: | Line 1,099: | ||
GOBACK |
GOBACK |
||
.</ |
.</syntaxhighlight> |
||
=={{header|CoffeeScript}}== |
=={{header|CoffeeScript}}== |
||
< |
<syntaxhighlight lang="coffeescript"> |
||
sum = (array) -> |
sum = (array) -> |
||
array.reduce (x, y) -> x + y |
array.reduce (x, y) -> x + y |
||
Line 428: | Line 1,108: | ||
product = (array) -> |
product = (array) -> |
||
array.reduce (x, y) -> x * y |
array.reduce (x, y) -> x * y |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|ColdFusion}}== |
=={{header|ColdFusion}}== |
||
Sum of an Array, |
Sum of an Array, |
||
< |
<syntaxhighlight lang="cfm"><cfset Variables.myArray = [1,2,3,4,5,6,7,8,9,10]> |
||
<cfoutput>#ArraySum(Variables.myArray)#</cfoutput></ |
<cfoutput>#ArraySum(Variables.myArray)#</cfoutput></syntaxhighlight> |
||
Product of an Array, |
Product of an Array, |
||
< |
<syntaxhighlight lang="cfm"><cfset Variables.myArray = [1,2,3,4,5,6,7,8,9,10]> |
||
<cfset Variables.Product = 1> |
<cfset Variables.Product = 1> |
||
<cfloop array="#Variables.myArray#" index="i"> |
<cfloop array="#Variables.myArray#" index="i"> |
||
<cfset Variables.Product *= i> |
<cfset Variables.Product *= i> |
||
</cfloop> |
</cfloop> |
||
<cfoutput>#Variables.Product#</cfoutput></ |
<cfoutput>#Variables.Product#</cfoutput></syntaxhighlight> |
||
=={{header|Common Lisp}}== |
=={{header|Common Lisp}}== |
||
< |
<syntaxhighlight lang="lisp">(let ((data #(1 2 3 4 5))) ; the array |
||
(values (reduce #'+ data) ; sum |
(values (reduce #'+ data) ; sum |
||
(reduce #'* data))) ; product</ |
(reduce #'* data))) ; product</syntaxhighlight> |
||
The loop macro also has support for sums. |
The loop macro also has support for sums. |
||
< |
<syntaxhighlight lang="lisp">(loop for i in '(1 2 3 4 5) sum i)</syntaxhighlight> |
||
=={{header|Crystal}}== |
|||
===Declarative=== |
|||
<syntaxhighlight lang="ruby"> |
|||
def sum_product(a) |
|||
{ a.sum(), a.product() } |
|||
end |
|||
</syntaxhighlight> |
|||
===Imperative=== |
|||
<syntaxhighlight lang="ruby"> |
|||
def sum_product_imperative(a) |
|||
sum, product = 0, 1 |
|||
a.each do |e| |
|||
sum += e |
|||
product *= e |
|||
end |
|||
{sum, product} |
|||
end |
|||
</syntaxhighlight> |
|||
<syntaxhighlight lang="ruby"> |
|||
require "benchmark" |
|||
Benchmark.ips do |x| |
|||
x.report("declarative") { sum_product [1, 2, 3, 4, 5] } |
|||
x.report("imperative") { sum_product_imperative [1, 2, 3, 4, 5] } |
|||
end |
|||
</syntaxhighlight> |
|||
<pre>declarative 8.1M (123.45ns) (± 2.99%) 65 B/op 1.30× slower |
|||
imperative 10.57M ( 94.61ns) (± 2.96%) 65 B/op fastest</pre> |
|||
=={{header|D}}== |
=={{header|D}}== |
||
< |
<syntaxhighlight lang="d">import std.stdio; |
||
void main() { |
void main() { |
||
Line 467: | Line 1,179: | ||
writeln("Sum: ", sum); |
writeln("Sum: ", sum); |
||
writeln("Product: ", prod); |
writeln("Product: ", prod); |
||
}</ |
}</syntaxhighlight> |
||
{{Out}} |
|||
Output: |
|||
<pre>Sum: 15 |
<pre>Sum: 15 |
||
Product: 120</pre> |
Product: 120</pre> |
||
Compute sum and product of array in one pass (same output): |
Compute sum and product of array in one pass (same output): |
||
< |
<syntaxhighlight lang="d">import std.stdio, std.algorithm, std.typecons; |
||
void main() { |
void main() { |
||
Line 482: | Line 1,194: | ||
writeln("Sum: ", r[0]); |
writeln("Sum: ", r[0]); |
||
writeln("Product: ", r[1]); |
writeln("Product: ", r[1]); |
||
}</ |
}</syntaxhighlight> |
||
=={{header|dc}}== |
|||
<syntaxhighlight lang="dc">1 3 5 7 9 11 13 0ss1sp[dls+sslp*spz0!=a]dsax[Sum: ]Plsp[Product: ]Plpp |
|||
Sum: 49 |
|||
Product: 135135</syntaxhighlight> |
|||
=={{header|Delphi}}== |
=={{header|Delphi}}== |
||
< |
<syntaxhighlight lang="delphi">program SumAndProductOfArray; |
||
{$APPTYPE CONSOLE} |
{$APPTYPE CONSOLE} |
||
Line 505: | Line 1,222: | ||
Write('Product: '); |
Write('Product: '); |
||
Writeln(lProduct); |
Writeln(lProduct); |
||
end.</ |
end.</syntaxhighlight> |
||
=={{header|E}}== |
=={{header|E}}== |
||
< |
<syntaxhighlight lang="e">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 } |
||
accum 1 for x in [1,2,3,4,5] { _ * x }</ |
accum 1 for x in [1,2,3,4,5] { _ * x }</syntaxhighlight> |
||
=={{header|EasyLang}}== |
|||
<syntaxhighlight lang="easylang"> |
|||
array[] = [ 5 1 19 25 12 1 14 7 ] |
|||
product = 1 |
|||
for item in array[] |
|||
sum += item |
|||
product *= item |
|||
. |
|||
print "Sum: " & sum |
|||
print "Product: " & product</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
Sum: 84 |
|||
Product: 2793000 |
|||
</pre> |
|||
=={{header|Eiffel}}== |
|||
<syntaxhighlight lang="eiffel"> |
|||
class |
|||
APPLICATION |
|||
create |
|||
make |
|||
feature {NONE} |
|||
make |
|||
local |
|||
test: ARRAY [INTEGER] |
|||
do |
|||
create test.make_empty |
|||
test := <<5, 1, 9, 7>> |
|||
io.put_string ("Sum: " + sum (test).out) |
|||
io.new_line |
|||
io.put_string ("Product: " + product (test).out) |
|||
end |
|||
sum (ar: ARRAY [INTEGER]): INTEGER |
|||
-- Sum of the items of the array 'ar'. |
|||
do |
|||
across |
|||
ar.lower |..| ar.upper as c |
|||
loop |
|||
Result := Result + ar [c.item] |
|||
end |
|||
end |
|||
product (ar: ARRAY [INTEGER]): INTEGER |
|||
-- Product of the items of the array 'ar'. |
|||
do |
|||
Result := 1 |
|||
across |
|||
ar.lower |..| ar.upper as c |
|||
loop |
|||
Result := Result * ar [c.item] |
|||
end |
|||
end |
|||
end |
|||
</syntaxhighlight> |
|||
{{Out}} |
|||
<pre>Sum of the elements of the array: 30 |
|||
Product of the elements of the array: 3840</pre> |
|||
=={{header|Elena}}== |
|||
ELENA 5.0: |
|||
<syntaxhighlight lang="elena">import system'routines; |
|||
import extensions; |
|||
public program() |
|||
{ |
|||
var list := new int[]{1, 2, 3, 4, 5 }; |
|||
var sum := list.summarize(new Integer()); |
|||
var product := list.accumulate(new Integer(1), (var,val => var * val)); |
|||
}</syntaxhighlight> |
|||
=={{header|Elixir}}== |
|||
When an accumulator is omitted, the first element of the collection is used as the initial value of acc. |
|||
<syntaxhighlight lang="elixir">iex(26)> Enum.reduce([1,2,3,4,5], 0, fn x,acc -> x+acc end) |
|||
15 |
|||
iex(27)> Enum.reduce([1,2,3,4,5], 1, fn x,acc -> x*acc end) |
|||
120 |
|||
iex(28)> Enum.reduce([1,2,3,4,5], fn x,acc -> x+acc end) |
|||
15 |
|||
iex(29)> Enum.reduce([1,2,3,4,5], fn x,acc -> x*acc end) |
|||
120 |
|||
iex(30)> Enum.reduce([], 0, fn x,acc -> x+acc end) |
|||
0 |
|||
iex(31)> Enum.reduce([], 1, fn x,acc -> x*acc end) |
|||
1 |
|||
iex(32)> Enum.reduce([], fn x,acc -> x+acc end) |
|||
** (Enum.EmptyError) empty error |
|||
(elixir) lib/enum.ex:1287: Enum.reduce/2 |
|||
iex(32)> Enum.reduce([], fn x,acc -> x*acc end) |
|||
** (Enum.EmptyError) empty error |
|||
(elixir) lib/enum.ex:1287: Enum.reduce/2</syntaxhighlight> |
|||
The function with sum |
|||
<syntaxhighlight lang="elixir">Enum.sum([1,2,3,4,5]) #=> 15</syntaxhighlight> |
|||
=={{header|Emacs Lisp}}== |
=={{header|Emacs Lisp}}== |
||
{{works with|XEmacs|version 21.5.21}} |
|||
< |
<syntaxhighlight lang="lisp">(let ((array [1 2 3 4 5])) |
||
(apply #'+ (append array nil)) |
|||
(apply #'* (append array nil)))</syntaxhighlight> |
|||
{{libheader|cl-lib}} |
|||
<syntaxhighlight lang="lisp">(require 'cl-lib) |
|||
(let ((array [1 2 3 4 5])) |
|||
===With a list=== |
|||
(cl-reduce #'+ array) |
|||
(cl-reduce #'* array))</syntaxhighlight> |
|||
{{libheader|seq.el}} |
|||
<lang lisp>(setq array '(1 2 3 4 5)) |
|||
(apply '+ array) |
|||
(apply '* array)</lang> |
|||
<syntaxhighlight lang="lisp">(require 'seq) |
|||
===With explicit conversion=== |
|||
(let ((array [1 2 3 4 5])) |
|||
( |
(seq-reduce #'+ array 0) |
||
( |
(seq-reduce #'* array 1))</syntaxhighlight> |
||
=={{header|Erlang}}== |
=={{header|Erlang}}== |
||
Using the standard libraries: |
Using the standard libraries: |
||
< |
<syntaxhighlight lang="erlang">% create the list: |
||
L = lists:seq(1, 10). |
L = lists:seq(1, 10). |
||
% and compute its sum: |
% and compute its sum: |
||
S = lists:sum(L). |
S = lists:sum(L). |
||
P = lists:foldl(fun (X, P) -> X * P end, 1, L).</ |
P = lists:foldl(fun (X, P) -> X * P end, 1, L).</syntaxhighlight> |
||
To compute sum and products in one pass: |
To compute sum and products in one pass: |
||
< |
<syntaxhighlight lang="erlang"> |
||
{Prod,Sum} = lists:foldl(fun (X, {P,S}) -> {P*X,S+X} end, {1,0}, lists:seq(1,10)).</ |
{Prod,Sum} = lists:foldl(fun (X, {P,S}) -> {P*X,S+X} end, {1,0}, lists:seq(1,10)).</syntaxhighlight> |
||
Or defining our own versions: |
Or defining our own versions: |
||
< |
<syntaxhighlight lang="erlang">-module(list_sum). |
||
-export([sum_rec/1, sum_tail/1]). |
-export([sum_rec/1, sum_tail/1]). |
||
Line 557: | Line 1,379: | ||
Acc; |
Acc; |
||
sum_tail([Head|Tail], Acc) -> |
sum_tail([Head|Tail], Acc) -> |
||
sum_tail(Tail, Head + Acc).</ |
sum_tail(Tail, Head + Acc).</syntaxhighlight> |
||
=={{header|Euler}}== |
|||
In Euler, a list must be assigned to a variable in order for it to be subscripted. |
|||
'''begin''' |
|||
'''new''' sumAndProduct; |
|||
'''new''' sumField; '''new''' productField; |
|||
sumAndProduct |
|||
<- ` '''formal''' array; |
|||
'''begin''' |
|||
'''new''' sum; '''new''' product; '''new''' i; '''new''' v; '''label''' arrayLoop; |
|||
v <- array; |
|||
sum <- 0; |
|||
product <- 1; |
|||
i <- 0; |
|||
arrayLoop: '''if''' [ i <- i + 1 ] <= '''length''' array '''then''' '''begin''' |
|||
sum <- sum + v[ i ]; |
|||
product <- product * v[ i ]; |
|||
'''goto''' arrayLoop |
|||
'''end''' '''else''' 0; |
|||
sumField <- 1; |
|||
productField <- 2; |
|||
( sum, product ) |
|||
'''end''' |
|||
'; |
|||
'''begin''' |
|||
'''new''' sp; |
|||
sp <- sumAndProduct( ( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ) ); |
|||
'''out''' sp[ sumField ]; |
|||
'''out''' sp[ productField ] |
|||
'''end''' |
|||
'''end''' $ |
|||
=={{header|Euphoria}}== |
=={{header|Euphoria}}== |
||
< |
<syntaxhighlight lang="euphoria">sequence array |
||
integer sum,prod |
integer sum,prod |
||
Line 573: | Line 1,426: | ||
printf(1,"sum is %d\n",sum) |
printf(1,"sum is %d\n",sum) |
||
printf(1,"prod is %d\n",prod)</ |
printf(1,"prod is %d\n",prod)</syntaxhighlight> |
||
{{Out}} |
|||
Output: |
|||
<pre> |
|||
sum is 15 |
sum is 15 |
||
prod is 120 |
prod is 120 |
||
</pre> |
|||
=={{header|F_Sharp|F#}}== |
=={{header|F_Sharp|F#}}== |
||
< |
<syntaxhighlight lang="fsharp"> |
||
let numbers = [| 1..10 |] |
let numbers = [| 1..10 |] |
||
let sum = numbers |> Array.sum |
let sum = numbers |> Array.sum |
||
let product = numbers |> Array. |
let product = numbers |> Array.reduce (*) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Factor}}== |
=={{header|Factor}}== |
||
< |
<syntaxhighlight lang="factor">1 5 1 <range> [ sum . ] [ product . ] bi |
||
15 120 |
15 120 |
||
{ 1 2 3 4 } [ sum ] [ product ] bi |
{ 1 2 3 4 } [ sum ] [ product ] bi |
||
10 24</ |
10 24</syntaxhighlight> |
||
sum and product are defined in the sequences vocabulary: |
sum and product are defined in the sequences vocabulary: |
||
< |
<syntaxhighlight lang="factor">: sum ( seq -- n ) 0 [ + ] reduce ; |
||
: product ( seq -- n ) 1 [ * ] reduce ;</ |
: product ( seq -- n ) 1 [ * ] reduce ;</syntaxhighlight> |
||
=={{header|FALSE}}== |
=={{header|FALSE}}== |
||
Strictly speaking, there are no arrays in FALSE. However, a number of elements on the stack could be considered an array. The implementation below assumes the length of the array on top of the stack, and the actual items below it. Note that this implementation does remove the "array" from the stack, so in case the original values need to be retained, a copy should be provided before executing this logic. |
Strictly speaking, there are no arrays in FALSE. However, a number of elements on the stack could be considered an array. The implementation below assumes the length of the array on top of the stack, and the actual items below it. Note that this implementation does remove the "array" from the stack, so in case the original values need to be retained, a copy should be provided before executing this logic. |
||
< |
<syntaxhighlight lang="false">1 2 3 4 5 {input "array"} |
||
5 {length of input} |
5 {length of input} |
||
0s: {sum} |
0s: {sum} |
||
Line 605: | Line 1,460: | ||
"Sum: "s;." |
"Sum: "s;." |
||
Product: "p;.</ |
Product: "p;.</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>Sum: 15 |
<pre>Sum: 15 |
||
Line 612: | Line 1,467: | ||
=={{header|Fantom}}== |
=={{header|Fantom}}== |
||
< |
<syntaxhighlight lang="fantom"> |
||
class Main |
class Main |
||
{ |
{ |
||
Line 645: | Line 1,500: | ||
} |
} |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Fermat}}== |
|||
<syntaxhighlight lang="fermat"> |
|||
[a]:=[(1,1,2,3,5,8,13)]; |
|||
!!Sigma<i=1,7>[a[i]]; |
|||
!!Prod<i=1,7>[a[i]]; |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
33 |
|||
3120 |
|||
</pre> |
|||
=={{header|Forth}}== |
=={{header|Forth}}== |
||
< |
<syntaxhighlight lang="forth">: third ( a b c -- a b c a ) 2 pick ; |
||
: reduce ( xt n addr cnt -- n' ) \ where xt ( a b -- n ) |
: reduce ( xt n addr cnt -- n' ) \ where xt ( a b -- n ) |
||
cells bounds do i @ third execute cell +loop nip ; |
cells bounds do i @ third execute cell +loop nip ; |
||
Line 655: | Line 1,522: | ||
' + 0 a 5 reduce . \ 15 |
' + 0 a 5 reduce . \ 15 |
||
' * 1 a 5 reduce . \ 120</ |
' * 1 a 5 reduce . \ 120</syntaxhighlight> |
||
=={{header|Fortran}}== |
=={{header|Fortran}}== |
||
In ISO Fortran 90 and later, use SUM and PRODUCT intrinsics: |
In ISO Fortran 90 and later, use SUM and PRODUCT intrinsics: |
||
< |
<syntaxhighlight lang="fortran">integer, dimension(10) :: a = (/ (i, i=1, 10) /) |
||
integer :: sresult, presult |
integer :: sresult, presult |
||
sresult = sum(a) |
sresult = sum(a) |
||
presult = product(a) |
presult = product(a)</syntaxhighlight> |
||
=={{header|FreeBASIC}}== |
|||
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64 |
|||
Dim a(1 To 4) As Integer = {1, 4, 6, 3} |
|||
Dim As Integer i, sum = 0, prod = 1 |
|||
For i = 1 To 4 |
|||
sum += a(i) |
|||
prod *= a(i) |
|||
Next |
|||
Print "Sum ="; sum |
|||
Print "Product ="; prod |
|||
Print |
|||
Print "Press any key to quit" |
|||
Sleep</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
Sum = 14 |
|||
Product = 72 |
|||
</pre> |
|||
=={{header|FreePascal}}== |
|||
<syntaxhighlight lang="pascal"> |
|||
program sumproduct; |
|||
var |
|||
a:array[0..4] of integer =(1,2,3,4,5); |
|||
i:integer; |
|||
sum :Cardinal = 0; |
|||
prod:Cardinal = 1; |
|||
begin |
|||
for i in a do |
|||
sum :=sum+i; |
|||
for i in a do |
|||
prod:=prod * i; |
|||
writeln('sum: ',sum); |
|||
writeln('prod:',prod); |
|||
end. |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
15 |
|||
120 |
|||
</pre> |
|||
=={{header|Frink}}== |
=={{header|Frink}}== |
||
< |
<syntaxhighlight lang="frink"> |
||
a = [1,2,3,5,7] |
a = [1,2,3,5,7] |
||
sum[a] |
sum[a] |
||
product[a] |
product[a] |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|FutureBasic}}== |
|||
Traditional |
|||
<syntaxhighlight lang="futurebasic"> |
|||
local fn Sum( mutArr as CFMutableArrayRef ) as float |
|||
NSInteger i, count, value = 0 |
|||
float sum = 0 |
|||
count = fn ArrayCount( mutArr ) |
|||
for i = 0 to count -1 |
|||
value = fn NumberIntegerValue( fn ArrayObjectAtIndex( mutArr, i ) ) |
|||
sum += value |
|||
next |
|||
end fn = sum |
|||
local fn Product( mutArr as CFMutableArrayRef ) as float |
|||
NSInteger i, count, value = 0 |
|||
float prod = 0 |
|||
count = fn ArrayCount( mutArr ) |
|||
for i = 0 to count -1 |
|||
value = fn NumberIntegerValue( fn ArrayObjectAtIndex( mutArr, i ) ) |
|||
prod *= value |
|||
next |
|||
end fn = prod |
|||
</syntaxhighlight> |
|||
Sum of array elements with key-value coding |
|||
<syntaxhighlight lang="futurebasic"> |
|||
local fn NumericalArraySum( array as CFArrayRef ) as CFNumberRef |
|||
end fn = fn ObjectValueForKeyPath( array, @"@sum.self" ) |
|||
printf @"%@", fn NumericalArraySum( @[@0.0454, @-1.3534, @0.345, @65, @-0.345, @1.35] ) |
|||
HandleEvents |
|||
</syntaxhighlight> |
|||
{{output}} |
|||
<pre> |
|||
65.042 |
|||
</pre> |
|||
=={{header|Fōrmulæ}}== |
|||
{{FormulaeEntry|page=https://formulae.org/?script=examples/Sum_and_product_of_an_array}} |
|||
'''Solution''' |
|||
[[File:Fōrmulæ - Sum and product of an array 01.png]] |
|||
'''Test cases''' |
|||
[[File:Fōrmulæ - Sum and product of an array 02.png]] |
|||
[[File:Fōrmulæ - Sum and product of an array 03.png]] |
|||
[[File:Fōrmulæ - Sum and product of an array 04.png]] |
|||
[[File:Fōrmulæ - Sum and product of an array 05.png]] |
|||
[[File:Fōrmulæ - Sum and product of an array 06.png]] |
|||
[[File:Fōrmulæ - Sum and product of an array 07.png]] |
|||
[[Wp:Empty sum|Empty sum]] and [[Wp:Empty_product|empty product]]: |
|||
[[File:Fōrmulæ - Sum and product of an array 08.png]] |
|||
[[File:Fōrmulæ - Sum and product of an array 09.png]] |
|||
=={{header|Gambas}}== |
|||
'''[https://gambas-playground.proko.eu/?gist=4a4bdc35d661e2dc22d66d88991bef95 Click this link to run this code]''' |
|||
<syntaxhighlight lang="gambas">Public Sub Main() |
|||
Dim iList As Integer[] = [1, 2, 3, 4, 5] |
|||
Dim iSum, iCount As Integer |
|||
Dim iPrd As Integer = 1 |
|||
For iCount = 0 To iList.Max |
|||
iSum += iList[iCount] |
|||
iPrd *= iList[iCount] |
|||
Next |
|||
Print "The Sum =\t" & iSum |
|||
Print "The Product =\t" & iPrd |
|||
End</syntaxhighlight> |
|||
Output: |
|||
<pre> |
|||
The Sum = 15 |
|||
The Product = 120 |
|||
</pre> |
|||
=={{header|GAP}}== |
=={{header|GAP}}== |
||
< |
<syntaxhighlight lang="gap">v := [1 .. 8]; |
||
Sum(v); |
Sum(v); |
||
Line 687: | Line 1,696: | ||
Product(v, n -> 1/n); |
Product(v, n -> 1/n); |
||
# 1/40320</ |
# 1/40320</syntaxhighlight> |
||
=={{header|GFA Basic}}== |
|||
<syntaxhighlight lang="basic"> |
|||
DIM a%(10) |
|||
' put some values into the array |
|||
FOR i%=1 TO 10 |
|||
a%(i%)=i% |
|||
NEXT i% |
|||
' |
|||
sum%=0 |
|||
product%=1 |
|||
FOR i%=1 TO 10 |
|||
sum%=sum%+a%(i%) |
|||
product%=product%*a%(i%) |
|||
NEXT i% |
|||
' |
|||
PRINT "Sum is ";sum% |
|||
PRINT "Product is ";product% |
|||
</syntaxhighlight> |
|||
=={{header|Go}}== |
=={{header|Go}}== |
||
;Implementation |
|||
<lang go>package main |
|||
<syntaxhighlight lang="go">package main |
|||
import "fmt" |
import "fmt" |
||
Line 701: | Line 1,735: | ||
} |
} |
||
fmt.Println(sum, prod) |
fmt.Println(sum, prod) |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
|||
<pre> |
|||
8 10 |
|||
</pre> |
|||
;Library |
|||
<syntaxhighlight lang="go">package main |
|||
import ( |
|||
"fmt" |
|||
"github.com/gonum/floats" |
|||
) |
|||
var a = []float64{1, 2, 5} |
|||
func main() { |
|||
fmt.Println("Sum: ", floats.Sum(a)) |
|||
fmt.Println("Product:", floats.Prod(a)) |
|||
}</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
Sum: 8 |
|||
Product: 10 |
|||
</pre> |
|||
=={{header|Groovy}}== |
=={{header|Groovy}}== |
||
Groovy adds a "sum()" method for collections, but not a "product()" method: |
Groovy adds a "sum()" method for collections, but not a "product()" method: |
||
< |
<syntaxhighlight lang="groovy">[1,2,3,4,5].sum()</syntaxhighlight> |
||
However, for general purpose "reduction" or "folding" operations, Groovy does provide an "inject()" method for collections similar to "inject" in Ruby. |
However, for general purpose "reduction" or "folding" operations, Groovy does provide an "inject()" method for collections similar to "inject" in Ruby. |
||
< |
<syntaxhighlight lang="groovy">[1,2,3,4,5].inject(0) { sum, val -> sum + val } |
||
[1,2,3,4,5].inject(1) { prod, val -> prod * val }</ |
[1,2,3,4,5].inject(1) { prod, val -> prod * val }</syntaxhighlight> |
||
You can also combine these operations: |
You can also combine these operations: |
||
< |
<syntaxhighlight lang="groovy">println ([1,2,3,4,5].inject([sum: 0, product: 1]) { result, value -> |
||
[sum: result.sum + value, product: result.product * value]})</ |
[sum: result.sum + value, product: result.product * value]})</syntaxhighlight> |
||
=={{header|GW-BASIC}}== |
=={{header|GW-BASIC}}== |
||
{{works with|Applesoft BASIC}} |
|||
{{works with|BASICA}} |
|||
{{works with|Chipmunk Basic|3.6.4}} |
|||
{{works with|GW-BASIC}} |
{{works with|GW-BASIC}} |
||
{{works with|QBasic}} |
{{works with|QBasic}} |
||
{{works with|MSX BASIC}} |
|||
< |
<syntaxhighlight lang="qbasic">10 REM Create an array with some test data in it |
||
20 DIM A(5) |
20 DIM A(5) |
||
30 FOR I = 1 TO 5: READ A(I): NEXT I |
30 FOR I = 1 TO 5: READ A(I): NEXT I |
||
Line 729: | Line 1,791: | ||
77 NEXT I |
77 NEXT I |
||
80 PRINT "The sum is "; S; |
80 PRINT "The sum is "; S; |
||
90 PRINT " and the product is "; P</ |
90 PRINT " and the product is "; P</syntaxhighlight> |
||
=={{header|Haskell}}== |
=={{header|Haskell}}== |
||
For lists, ''sum'' and ''product'' are already defined in the Prelude: |
For lists, ''sum'' and ''product'' are already defined in the Prelude: |
||
< |
<syntaxhighlight lang="haskell">values = [1..10] |
||
s = sum values -- the easy way |
s = sum values -- the easy way |
||
p = product values |
p = product values |
||
s1 = foldl (+) 0 values -- the hard way |
|||
p1 = foldl (*) 1 values</syntaxhighlight> |
|||
To do the same for an array, just convert it lazily to a list: |
To do the same for an array, just convert it lazily to a list: |
||
< |
<syntaxhighlight lang="haskell">import Data.Array |
||
values = listArray (1,10) [1..10] |
values = listArray (1,10) [1..10] |
||
s = sum . elems $ values |
s = sum . elems $ values |
||
p = product . elems $ values</ |
p = product . elems $ values</syntaxhighlight> |
||
Or perhaps: |
|||
<syntaxhighlight lang="haskell">import Data.Array (listArray, elems) |
|||
main :: IO () |
|||
main = mapM_ print $ [sum, product] <*> [elems $ listArray (1, 10) [11 .. 20]]</syntaxhighlight> |
|||
{{Out}} |
|||
<pre>155 |
|||
670442572800</pre> |
|||
=={{header|HicEst}}== |
=={{header|HicEst}}== |
||
< |
<syntaxhighlight lang="hicest">array = $ ! 1, 2, ..., LEN(array) |
||
sum = SUM(array) |
sum = SUM(array) |
||
Line 758: | Line 1,829: | ||
ENDDO |
ENDDO |
||
WRITE(ClipBoard, Name) n, sum, product ! n=100; sum=5050; product=9.33262154E157;</ |
WRITE(ClipBoard, Name) n, sum, product ! n=100; sum=5050; product=9.33262154E157;</syntaxhighlight> |
||
=={{header|IDL}}== |
|||
<lang idl>array = [3,6,8] |
|||
print,total(array) |
|||
print,product(array)</lang> |
|||
=={{header|Icon}} and {{header|Unicon}}== |
=={{header|Icon}} and {{header|Unicon}}== |
||
The program below prints the sum and product of the arguments to the program. |
The program below prints the sum and product of the arguments to the program. |
||
< |
<syntaxhighlight lang="icon">procedure main(arglist) |
||
every ( sum := 0 ) +:= !arglist |
every ( sum := 0 ) +:= !arglist |
||
every ( prod := 1 ) *:= !arglist |
every ( prod := 1 ) *:= !arglist |
||
write("sum := ", sum,", prod := ",prod) |
write("sum := ", sum,", prod := ",prod) |
||
end</ |
end</syntaxhighlight> |
||
=={{header|IDL}}== |
|||
<syntaxhighlight lang="idl">array = [3,6,8] |
|||
print,total(array) |
|||
print,product(array)</syntaxhighlight> |
|||
=={{header|Inform 7}}== |
=={{header|Inform 7}}== |
||
< |
<syntaxhighlight lang="inform7">Sum And Product is a room. |
||
To decide which number is the sum of (N - number) and (M - number) (this is summing): |
To decide which number is the sum of (N - number) and (M - number) (this is summing): |
||
Line 785: | Line 1,856: | ||
let L be {1, 2, 3, 4, 5}; |
let L be {1, 2, 3, 4, 5}; |
||
say "List: [L in brace notation], sum = [summing reduction of L], product = [production reduction of L]."; |
say "List: [L in brace notation], sum = [summing reduction of L], product = [production reduction of L]."; |
||
end the story.</ |
end the story.</syntaxhighlight> |
||
=={{header|J}}== |
=={{header|J}}== |
||
Simple approach:<syntaxhighlight lang="j"> (+/,*/) 2 3 5 7 |
|||
<lang j>sum =: +/ |
|||
17 210</syntaxhighlight> |
|||
product =: */</lang> |
|||
<hr /> |
|||
Longer exposition: |
|||
<syntaxhighlight lang="j">sum =: +/ |
|||
product =: */</syntaxhighlight> |
|||
For example: |
For example: |
||
< |
<syntaxhighlight lang="j"> sum 1 3 5 7 9 11 13 |
||
49 |
49 |
||
product 1 3 5 7 9 11 13 |
product 1 3 5 7 9 11 13 |
||
Line 815: | Line 1,893: | ||
466 472 462 |
466 472 462 |
||
product"1 a |
product"1 a |
||
5.53041e15 9.67411e15 1.93356e15</ |
5.53041e15 9.67411e15 1.93356e15</syntaxhighlight> |
||
=={{header|Java}}== |
=={{header|Java}}== |
||
{{works with|Java|1.5+}} |
{{works with|Java|1.5+}} |
||
< |
<syntaxhighlight lang="java5">public class SumProd |
||
{ |
{ |
||
public static void main(final String[] args) |
public static void main(final String[] args) |
||
Line 832: | Line 1,910: | ||
} |
} |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
{{works with|Java|1.8+}} |
{{works with|Java|1.8+}} |
||
< |
<syntaxhighlight lang="java5">import java.util.Arrays; |
||
public class SumProd |
public class SumProd |
||
Line 846: | Line 1,924: | ||
System.out.printf("product = %d\n", Arrays.stream(arg).reduce(1, (a, b) -> a * b)); |
System.out.printf("product = %d\n", Arrays.stream(arg).reduce(1, (a, b) -> a * b)); |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 855: | Line 1,933: | ||
=={{header|JavaScript}}== |
=={{header|JavaScript}}== |
||
===ES5=== |
|||
<lang javascript>var array = [1, 2, 3, 4, 5], |
|||
<syntaxhighlight lang="javascript">var array = [1, 2, 3, 4, 5], |
|||
sum = 0, |
sum = 0, |
||
prod = 1, |
prod = 1, |
||
Line 863: | Line 1,942: | ||
prod *= array[i]; |
prod *= array[i]; |
||
} |
} |
||
alert(sum + ' ' + prod);</ |
alert(sum + ' ' + prod);</syntaxhighlight> |
||
{{Works with|Javascript|1.8}} |
{{Works with|Javascript|1.8}} |
||
Where supported, the reduce method can also be used: |
Where supported, the reduce method can also be used: |
||
< |
<syntaxhighlight lang="javascript">var array = [1, 2, 3, 4, 5], |
||
sum = array.reduce(function (a, b) { |
sum = array.reduce(function (a, b) { |
||
return a + b; |
return a + b; |
||
Line 875: | Line 1,954: | ||
return a * b; |
return a * b; |
||
}, 1); |
}, 1); |
||
alert(sum + ' ' + prod);</ |
alert(sum + ' ' + prod);</syntaxhighlight> |
||
===ES6=== |
|||
<syntaxhighlight lang="javascript">(() => { |
|||
'use strict'; |
|||
// sum :: (Num a) => [a] -> a |
|||
const sum = xs => xs.reduce((a, x) => a + x, 0); |
|||
// product :: (Num a) => [a] -> a |
|||
const product = xs => xs.reduce((a, x) => a * x, 1); |
|||
// TEST |
|||
// show :: a -> String |
|||
const show = x => JSON.stringify(x, null, 2); |
|||
return show( |
|||
[sum, product] |
|||
.map(f => f([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])) |
|||
); |
|||
})();</syntaxhighlight> |
|||
{{Out}} |
|||
<pre>[ |
|||
55, |
|||
3628800 |
|||
]</pre> |
|||
=={{header|Joy}}== |
|||
<syntaxhighlight lang="joy">[1 2 3 4 5] 0 [+] fold.</syntaxhighlight> |
|||
<syntaxhighlight lang="joy">[1 2 3 4 5] 1 [*] fold.</syntaxhighlight> |
|||
=={{header|jq}}== |
|||
The builtin filter, add/0, computes the sum of an array: |
|||
<syntaxhighlight lang="jq">[4,6,8] | add |
|||
# => 18</syntaxhighlight> |
|||
<syntaxhighlight lang="jq">[range(2;5) * 2] | add |
|||
# => 18</syntaxhighlight> |
|||
An efficient companion filter for computing the product of the items in an array can be defined as follows: |
|||
<syntaxhighlight lang="jq">def prod: reduce .[] as $i (1; . * $i);</syntaxhighlight> |
|||
Examples: |
|||
<syntaxhighlight lang="jq">[4,6,8] | prod |
|||
# => 192</syntaxhighlight> |
|||
10! |
|||
<syntaxhighlight lang="jq">[range(1;11)] | prod |
|||
# =>3628800</syntaxhighlight> |
|||
=={{header|Julia}}== |
=={{header|Julia}}== |
||
< |
<syntaxhighlight lang="julia">julia> sum([4,6,8]) |
||
18 |
18 |
||
julia> +((1:10)...) |
|||
55 |
|||
julia +([1,2,3]...) |
|||
6 |
|||
julia> prod([4,6,8]) |
julia> prod([4,6,8]) |
||
192</ |
192</syntaxhighlight> |
||
=={{header|K}}== |
|||
<syntaxhighlight lang="k"> sum: {+/}x |
|||
product: {*/}x |
|||
a: 1 3 5 7 9 11 13 |
|||
sum a |
|||
49 |
|||
product a |
|||
135135</syntaxhighlight> |
|||
It is easy to see the relationship of K to J here. |
|||
=={{header|Kotlin}}== |
|||
<syntaxhighlight lang="scala">// version 1.1.2 |
|||
fun main(args: Array<String>) { |
|||
val a = intArrayOf(1, 5, 8, 11, 15) |
|||
println("Array contains : ${a.contentToString()}") |
|||
val sum = a.sum() |
|||
println("Sum is $sum") |
|||
val product = a.fold(1) { acc, i -> acc * i } |
|||
println("Product is $product") |
|||
}</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
Array contains : [1, 5, 8, 11, 15] |
|||
Sum is 40 |
|||
Product is 6600 |
|||
</pre> |
|||
=={{header|Lambdatalk}}== |
|||
<syntaxhighlight lang="lisp"> |
|||
{A.serie start end [step]} creates a sequence from start to end with optional step |
|||
{A.new words} creates an array from a sequence of words |
|||
{A.toS array} creates a sequence from the items of an array |
|||
{long_add x y} returns the sum of two integers of any size |
|||
{long_mult x y} returns the product of two integers of any size |
|||
{def A {A.new {S.serie 1 10}}} -> [1,2,3,4,5,6,7,8,9,10] |
|||
{+ {A.toS {A}}} -> 55 |
|||
{* {A.toS {A}}} -> 3628800 |
|||
{def B {A.new {S.serie 1 100}}} -> [1,2,3,4,5,6,7,8,9,10,...,95,96,97,98,99,100] |
|||
{S.reduce long_add {A.toS {B}}} -> 5050 |
|||
{S.reduce long_mult {A.toS {B}}} -> |
|||
9332621544394415268169923885626670049071596826438162146859296389521759999322991 |
|||
5608941463976156518286253697920827223758251185210916864000000000000000000000000 |
|||
</syntaxhighlight> |
|||
=={{header|Lang}}== |
|||
<syntaxhighlight lang="lang"> |
|||
&values = fn.arrayGenerateFrom(fn.inc, 5) |
|||
fn.println(fn.arrayReduce(&values, 0, fn.add)) |
|||
# Output: 15 |
|||
fn.println(fn.arrayReduce(&values, 1, fn.mul)) |
|||
# Output: 120 |
|||
</syntaxhighlight> |
|||
=={{header|Lang5}}== |
=={{header|Lang5}}== |
||
< |
<syntaxhighlight lang="lang5">4 iota 1 + dup |
||
'+ reduce |
'+ reduce |
||
'* reduce</ |
'* reduce</syntaxhighlight> |
||
=={{header|langur}}== |
|||
<syntaxhighlight lang="langur">val .list = series 19 |
|||
writeln " list: ", .list |
|||
writeln " sum: ", fold fn{+}, .list |
|||
writeln "product: ", fold fn{*}, .list |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> list: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19] |
|||
sum: 190 |
|||
product: 121645100408832000</pre> |
|||
=={{header|Lasso}}== |
=={{header|Lasso}}== |
||
< |
<syntaxhighlight lang="lasso">local(x = array(1,2,3,4,5,6,7,8,9,10)) |
||
// sum of array elements |
// sum of array elements |
||
'Sum: ' |
'Sum: ' |
||
Line 902: | Line 2,105: | ||
local(product = 1) |
local(product = 1) |
||
with n in #x do => { #product *= #n } |
with n in #x do => { #product *= #n } |
||
#product</ |
#product</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>Sum: 55 |
<pre>Sum: 55 |
||
Line 908: | Line 2,111: | ||
=={{header|Liberty BASIC}}== |
=={{header|Liberty BASIC}}== |
||
< |
<syntaxhighlight lang="lb">Dim array(19) |
||
For i = 0 To 19 |
For i = 0 To 19 |
||
Line 922: | Line 2,125: | ||
Print "Sum is " + str$(sum) |
Print "Sum is " + str$(sum) |
||
Print "Product is " + str$(product)</ |
Print "Product is " + str$(product)</syntaxhighlight> |
||
=={{header|Lingo}}== |
|||
<syntaxhighlight lang="lingo">on sum (intList) |
|||
res = 0 |
|||
repeat with v in intList |
|||
res = res + v |
|||
end repeat |
|||
return res |
|||
end |
|||
on product (intList) |
|||
res = 1 |
|||
repeat with v in intList |
|||
res = res * v |
|||
end repeat |
|||
return res |
|||
end</syntaxhighlight> |
|||
=={{header|LiveCode}}== |
|||
<syntaxhighlight lang="livecode">//sum |
|||
put "1,2,3,4" into nums |
|||
split nums using comma |
|||
answer sum(nums) |
|||
// product |
|||
local prodNums |
|||
repeat for each element n in nums |
|||
if prodNums is empty then |
|||
put n into prodNums |
|||
else |
|||
multiply prodnums by n |
|||
end if |
|||
end repeat |
|||
answer prodnums</syntaxhighlight> |
|||
=={{header|Logo}}== |
=={{header|Logo}}== |
||
< |
<syntaxhighlight lang="logo">print apply "sum arraytolist {1 2 3 4 5} |
||
print apply "product arraytolist {1 2 3 4 5}</ |
print apply "product arraytolist {1 2 3 4 5}</syntaxhighlight> |
||
=={{header|LOLCODE}}== |
|||
<syntaxhighlight lang="lolcode">HAI 1.2 |
|||
I HAS A Nums ITZ A BUKKIT |
|||
Nums HAS A Length ITZ 0 |
|||
Nums HAS A SRS Nums'Z Length ITZ 1 |
|||
Nums'Z Length R SUM OF Nums'Z Length AN 1 |
|||
Nums HAS A SRS Nums'Z Length ITZ 2 |
|||
Nums'Z Length R SUM OF Nums'Z Length AN 1 |
|||
Nums HAS A SRS Nums'Z Length ITZ 3 |
|||
Nums'Z Length R SUM OF Nums'Z Length AN 1 |
|||
Nums HAS A SRS Nums'Z Length ITZ 5 |
|||
Nums'Z Length R SUM OF Nums'Z Length AN 1 |
|||
Nums HAS A SRS Nums'Z Length ITZ 7 |
|||
Nums'Z Length R SUM OF Nums'Z Length AN 1 |
|||
I HAS A Added ITZ 0 |
|||
I HAS A Timesed ITZ 1 |
|||
I HAS A Num |
|||
IM IN YR Loop UPPIN YR Index WILE DIFFRINT Index AN Nums'Z Length |
|||
Num R Nums'Z SRS Index |
|||
Added R SUM OF Added AN Num |
|||
Timesed R PRODUKT OF Timesed AN Num |
|||
IM OUTTA YR Loop |
|||
VISIBLE "Sum = " ! |
|||
VISIBLE Added |
|||
VISIBLE "Product = " ! |
|||
VISIBLE Timesed |
|||
KTHXBYE</syntaxhighlight> |
|||
{{Out}} |
|||
<pre>Sum = 18 |
|||
Product = 210</pre> |
|||
=={{header|Lua}}== |
=={{header|Lua}}== |
||
< |
<syntaxhighlight lang="lua"> |
||
function sumf(a, ...) return a and a + sumf(...) or 0 end |
function sumf(a, ...) return a and a + sumf(...) or 0 end |
||
function sumt(t) return sumf(unpack(t)) end |
function sumt(t) return sumf(unpack(t)) end |
||
Line 935: | Line 2,206: | ||
print(sumt{1, 2, 3, 4, 5}) |
print(sumt{1, 2, 3, 4, 5}) |
||
print(prodt{1, 2, 3, 4, 5})</ |
print(prodt{1, 2, 3, 4, 5})</syntaxhighlight> |
||
<syntaxhighlight lang="lua"> |
|||
function table.sum(arr, length) |
|||
--same as if <> then <> else <> |
|||
return length == 1 and arr[1] or arr[length] + table.sum(arr, length -1) |
|||
end |
|||
function table.product(arr, length) |
|||
return length == 1 and arr[1] or arr[length] * table.product(arr, length -1) |
|||
end |
|||
t = {1,2,3} |
|||
print(table.sum(t,#t)) |
|||
print(table.product(t,3)) |
|||
</syntaxhighlight> |
|||
=={{header|Lucid}}== |
=={{header|Lucid}}== |
||
prints a running sum and product of sequence 1,2,3... |
prints a running sum and product of sequence 1,2,3... |
||
< |
<syntaxhighlight lang="lucid">[%sum,product%] |
||
where |
where |
||
x = 1 fby x + 1; |
x = 1 fby x + 1; |
||
sum = 0 fby sum + x; |
sum = 0 fby sum + x; |
||
product = 1 fby product * x |
product = 1 fby product * x |
||
end</ |
end</syntaxhighlight> |
||
=={{header|Mathematica}}== |
|||
=={{header|M2000 Interpreter}}== |
|||
<syntaxhighlight lang="m2000 interpreter"> |
|||
Module Checkit { |
|||
a = (1,2,3,4,5,6,7,8,9,10) |
|||
print a#sum() = 55 |
|||
sum = lambda->{push number+number} |
|||
product = lambda->{Push number*number} |
|||
print a#fold(lambda->{Push number*number}, 1), a#fold(lambda->{push number+number},0) |
|||
dim a(2,2) = 5 |
|||
Print a()#sum() = 20 |
|||
} |
|||
checkit |
|||
</syntaxhighlight> |
|||
=={{header|Maple}}== |
|||
<syntaxhighlight lang="maple">a := Array([1, 2, 3, 4, 5, 6]); |
|||
add(a); |
|||
mul(a);</syntaxhighlight> |
|||
=={{header|Mathematica}}/{{header|Wolfram Language}}== |
|||
Mathematica provides many ways of doing the sum of an array (any kind of numbers or symbols): |
Mathematica provides many ways of doing the sum of an array (any kind of numbers or symbols): |
||
< |
<syntaxhighlight lang="mathematica">a = {1, 2, 3, 4, 5} |
||
Plus @@ a |
Plus @@ a |
||
Apply[Plus, a] |
Apply[Plus, a] |
||
Line 954: | Line 2,260: | ||
a // Total |
a // Total |
||
Sum[a[[i]], {i, 1, Length[a]}] |
Sum[a[[i]], {i, 1, Length[a]}] |
||
Sum[i, {i, a}]</ |
Sum[i, {i, a}]</syntaxhighlight> |
||
all give 15. For product we also have a couple of choices: |
all give 15. For product we also have a couple of choices: |
||
< |
<syntaxhighlight lang="mathematica">a = {1, 2, 3, 4, 5} |
||
Times @@ a |
Times @@ a |
||
Apply[Times, a] |
Apply[Times, a] |
||
Product[a[[i]], {i, 1, Length[a]}] |
Product[a[[i]], {i, 1, Length[a]}] |
||
Product[i, {i, a}]</ |
Product[i, {i, a}]</syntaxhighlight> |
||
all give 120. |
all give 120. |
||
Line 967: | Line 2,273: | ||
Sample Usage: |
Sample Usage: |
||
< |
<syntaxhighlight lang="matlab">>> array = [1 2 3;4 5 6;7 8 9] |
||
array = |
array = |
||
Line 1,001: | Line 2,307: | ||
6 |
6 |
||
120 |
120 |
||
504</ |
504</syntaxhighlight> |
||
=={{header|Maxima}}== |
=={{header|Maxima}}== |
||
< |
<syntaxhighlight lang="maxima">lreduce("+", [1, 2, 3, 4, 5, 6, 7, 8]); |
||
36 |
36 |
||
lreduce("*", [1, 2, 3, 4, 5, 6, 7, 8]); |
lreduce("*", [1, 2, 3, 4, 5, 6, 7, 8]); |
||
40320</ |
40320</syntaxhighlight> |
||
=={{header|MAXScript}}== |
=={{header|MAXScript}}== |
||
< |
<syntaxhighlight lang="maxscript">arr = #(1, 2, 3, 4, 5) |
||
sum = 0 |
sum = 0 |
||
for i in arr do sum += i |
for i in arr do sum += i |
||
product = 1 |
product = 1 |
||
for i in arr do product *= i</ |
for i in arr do product *= i</syntaxhighlight> |
||
=={{header|min}}== |
|||
{{works with|min|0.19.3}} |
|||
<syntaxhighlight lang="min">(1 2 3 4 5) ((sum) (1 '* reduce)) cleave |
|||
"Sum: $1\nProduct: $2" get-stack % puts</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
Sum: 15 |
|||
Product: 120 |
|||
</pre> |
|||
=={{header|МК-61/52}}== |
=={{header|МК-61/52}}== |
||
<lang>^ 1 ПE + П0 КИП0 x#0 18 ^ ИПD |
<syntaxhighlight lang="text">^ 1 ПE + П0 КИП0 x#0 18 ^ ИПD |
||
+ ПD <-> ИПE * ПE БП 05 С/П</ |
+ ПD <-> ИПE * ПE БП 05 С/П</syntaxhighlight> |
||
''Instruction'': РX - array length, Р1:РC - array, РD and РE - sum and product of an array. |
''Instruction'': РX - array length, Р1:РC - array, РD and РE - sum and product of an array. |
||
=={{header|Modula-3}}== |
=={{header|Modula-3}}== |
||
< |
<syntaxhighlight lang="modula3">MODULE Sumprod EXPORTS Main; |
||
FROM IO IMPORT Put; |
FROM IO IMPORT Put; |
||
Line 1,042: | Line 2,357: | ||
Put("Sum of array: " & Int(sum) & "\n"); |
Put("Sum of array: " & Int(sum) & "\n"); |
||
Put("Product of array: " & Int(prod) & "\n"); |
Put("Product of array: " & Int(prod) & "\n"); |
||
END Sumprod.</ |
END Sumprod.</syntaxhighlight> |
||
{{Out}} |
|||
Output: |
|||
<pre>Sum of array: 15 |
<pre>Sum of array: 15 |
||
Product of array: 120</pre> |
Product of array: 120</pre> |
||
=={{header|MUMPS}}== |
=={{header|MUMPS}}== |
||
<syntaxhighlight lang="mumps"> |
|||
<lang MUMPS> |
|||
SUMPROD(A) |
SUMPROD(A) |
||
;Compute the sum and product of the numbers in the array A |
;Compute the sum and product of the numbers in the array A |
||
Line 1,060: | Line 2,375: | ||
WRITE !,"The product of the array is "_PROD |
WRITE !,"The product of the array is "_PROD |
||
KILL SUM,PROD,POS |
KILL SUM,PROD,POS |
||
QUIT</ |
QUIT</syntaxhighlight> |
||
Example: <pre> |
Example: <pre> |
||
USER>SET C(-1)=2,C("A")=3,C(42)=1,C(0)=7 |
USER>SET C(-1)=2,C("A")=3,C(42)=1,C(0)=7 |
||
Line 1,081: | Line 2,396: | ||
=={{header|Nemerle}}== |
=={{header|Nemerle}}== |
||
As mentioned for some of the other functional languages, it seems more natural to work with lists in Nemerle, but as the task specifies working on an array, this solution will work on either. |
As mentioned for some of the other functional languages, it seems more natural to work with lists in Nemerle, but as the task specifies working on an array, this solution will work on either. |
||
< |
<syntaxhighlight lang="nemerle">using System; |
||
using System.Console; |
using System.Console; |
||
using System.Collections.Generic; |
using System.Collections.Generic; |
||
Line 1,110: | Line 2,425: | ||
WriteLine("Sum is: {0}\tProduct is: {1}", suml, proda); |
WriteLine("Sum is: {0}\tProduct is: {1}", suml, proda); |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|NetRexx}}== |
=={{header|NetRexx}}== |
||
< |
<syntaxhighlight lang="netrexx">/* NetRexx */ |
||
options replace format comments java crossref savelog symbols binary |
options replace format comments java crossref savelog symbols binary |
||
Line 1,137: | Line 2,452: | ||
return |
return |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{Out}} |
|||
;Output |
|||
<pre> |
<pre> |
||
Sum and product of 1,2,3,4,5,6,7,8,9,10: |
Sum and product of 1,2,3,4,5,6,7,8,9,10: |
||
Line 1,144: | Line 2,459: | ||
Product: 3628800 |
Product: 3628800 |
||
</pre> |
</pre> |
||
=={{header|NewLISP}}== |
|||
<syntaxhighlight lang="newlisp">(setq a '(1 2 3 4 5)) |
|||
(apply + a) |
|||
(apply * a)</syntaxhighlight> |
|||
=={{header|Nial}}== |
=={{header|Nial}}== |
||
Nial being an array language, what applies to individual elements are extended to cover array operations by default strand notation |
Nial being an array language, what applies to individual elements are extended to cover array operations by default strand notation |
||
< |
<syntaxhighlight lang="nial">+ 1 2 3 |
||
= 6 |
= 6 |
||
* 1 2 3 |
* 1 2 3 |
||
= 6</ |
= 6</syntaxhighlight> |
||
array notation |
array notation |
||
<lang |
<syntaxhighlight lang="nial">+ [1,2,3]</syntaxhighlight> |
||
grouped notation |
grouped notation |
||
< |
<syntaxhighlight lang="nial">(* 1 2 3) |
||
= 6 |
= 6 |
||
* (1 2 3) |
* (1 2 3) |
||
= 6</ |
= 6</syntaxhighlight> |
||
(All these notations are equivalent) |
(All these notations are equivalent) |
||
=={{header| |
=={{header|Nim}}== |
||
< |
<syntaxhighlight lang="nim">var xs = [1, 2, 3, 4, 5, 6] |
||
var sum, product: int |
var sum, product: int |
||
Line 1,169: | Line 2,489: | ||
for x in xs: |
for x in xs: |
||
sum += x |
sum += x |
||
product *= x</ |
product *= x</syntaxhighlight> |
||
Or functionally: |
Or functionally: |
||
< |
<syntaxhighlight lang="nim">import sequtils |
||
let |
let |
||
xs = |
xs = [1, 2, 3, 4, 5, 6] |
||
sum = xs.foldl(a + b) |
sum = xs.foldl(a + b) |
||
product = xs.foldl(a * b)</ |
product = xs.foldl(a * b)</syntaxhighlight> |
||
Or using a math function: |
|||
<syntaxhighlight lang="nim">import math |
|||
let numbers = [1, 5, 4] |
|||
let total = sum(numbers) |
|||
var product = 1 |
|||
for n in numbers: |
|||
product *= n</syntaxhighlight> |
|||
=={{header|Objeck}}== |
=={{header|Objeck}}== |
||
< |
<syntaxhighlight lang="objeck"> |
||
sum := 0; |
sum := 0; |
||
prod := 1; |
prod := 1; |
||
Line 1,188: | Line 2,518: | ||
prod *= arg[i]; |
prod *= arg[i]; |
||
}; |
}; |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Objective-C}}== |
=={{header|Objective-C}}== |
||
{{works with|GCC|4.0.1 (apple)}} |
{{works with|GCC|4.0.1 (apple)}} |
||
Sum: |
Sum: |
||
< |
<syntaxhighlight lang="objc">- (float) sum:(NSMutableArray *)array |
||
{ |
{ |
||
int i, sum, value; |
int i, sum, value; |
||
Line 1,205: | Line 2,535: | ||
return suml; |
return suml; |
||
}</ |
}</syntaxhighlight> |
||
Product: |
Product: |
||
< |
<syntaxhighlight lang="objc">- (float) prod:(NSMutableArray *)array |
||
{ |
{ |
||
int i, prod, value; |
int i, prod, value; |
||
Line 1,219: | Line 2,549: | ||
return suml; |
return suml; |
||
}</ |
}</syntaxhighlight> |
||
=={{header|OCaml}}== |
=={{header|OCaml}}== |
||
===Arrays=== |
===Arrays=== |
||
< |
<syntaxhighlight lang="ocaml">(* ints *) |
||
let a = [| 1; 2; 3; 4; 5 |];; |
let a = [| 1; 2; 3; 4; 5 |];; |
||
Array.fold_left (+) 0 a;; |
Array.fold_left (+) 0 a;; |
||
Line 1,230: | Line 2,560: | ||
let a = [| 1.0; 2.0; 3.0; 4.0; 5.0 |];; |
let a = [| 1.0; 2.0; 3.0; 4.0; 5.0 |];; |
||
Array.fold_left (+.) 0.0 a;; |
Array.fold_left (+.) 0.0 a;; |
||
Array.fold_left ( *.) 1.0 a;;</ |
Array.fold_left ( *.) 1.0 a;;</syntaxhighlight> |
||
===Lists=== |
===Lists=== |
||
< |
<syntaxhighlight lang="ocaml">(* ints *) |
||
let x = [1; 2; 3; 4; 5];; |
let x = [1; 2; 3; 4; 5];; |
||
List.fold_left (+) 0 x;; |
List.fold_left (+) 0 x;; |
||
Line 1,239: | Line 2,569: | ||
let x = [1.0; 2.0; 3.0; 4.0; 5.0];; |
let x = [1.0; 2.0; 3.0; 4.0; 5.0];; |
||
List.fold_left (+.) 0.0 x;; |
List.fold_left (+.) 0.0 x;; |
||
List.fold_left ( *.) 1.0 x;;</ |
List.fold_left ( *.) 1.0 x;;</syntaxhighlight> |
||
=={{header|Octave}}== |
=={{header|Octave}}== |
||
< |
<syntaxhighlight lang="octave">a = [ 1, 2, 3, 4, 5, 6 ]; |
||
b = [ 10, 20, 30, 40, 50, 60 ]; |
b = [ 10, 20, 30, 40, 50, 60 ]; |
||
vsum = a + b; |
vsum = a + b; |
||
vprod = a .* b;</ |
vprod = a .* b;</syntaxhighlight> |
||
=={{header|Oforth}}== |
|||
<syntaxhighlight lang="oforth">[1, 2, 3, 4, 5 ] sum println |
|||
[1, 3, 5, 7, 9 ] prod println</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
15 |
|||
945 |
|||
</pre> |
|||
=={{header|Ol}}== |
|||
<syntaxhighlight lang="scheme"> |
|||
(print (fold + 0 '(1 2 3 4 5))) |
|||
(print (fold * 1 '(1 2 3 4 5))) |
|||
</syntaxhighlight> |
|||
=={{header|ooRexx}}== |
|||
{{trans|REXX}} |
|||
<syntaxhighlight lang="oorexx">a=.my_array~new(20) |
|||
do i=1 To 20 |
|||
a[i]=i |
|||
End |
|||
s=a~makestring((LINE),',') |
|||
Say s |
|||
Say ' sum='a~sum |
|||
Say 'product='a~prod |
|||
::class my_array subclass array |
|||
::method sum |
|||
sum=0 |
|||
Do i=1 To self~dimension(1) |
|||
sum+=self[i] |
|||
End |
|||
Return sum |
|||
::method prod |
|||
Numeric Digits 30 |
|||
prod=1 |
|||
Do i=1 To self~dimension(1) |
|||
prod*=self[i] |
|||
End |
|||
Return prod</syntaxhighlight> |
|||
{{out}} |
|||
<pre>1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20 |
|||
sum=210 |
|||
product=2432902008176640000</pre> |
|||
=={{header|Oz}}== |
=={{header|Oz}}== |
||
Calculations like this are typically done on lists, not on arrays: |
Calculations like this are typically done on lists, not on arrays: |
||
< |
<syntaxhighlight lang="oz">declare |
||
Xs = [1 2 3 4 5] |
Xs = [1 2 3 4 5] |
||
Sum = {FoldL Xs Number.'+' 0} |
Sum = {FoldL Xs Number.'+' 0} |
||
Line 1,254: | Line 2,631: | ||
in |
in |
||
{Show Sum} |
{Show Sum} |
||
{Show Product}</ |
{Show Product}</syntaxhighlight> |
||
If you are actually working with arrays, a more imperative approach seems natural: |
If you are actually working with arrays, a more imperative approach seems natural: |
||
< |
<syntaxhighlight lang="oz">declare |
||
Arr = {Array.new 1 3 0} |
Arr = {Array.new 1 3 0} |
||
Sum = {NewCell 0} |
Sum = {NewCell 0} |
||
Line 1,268: | Line 2,645: | ||
Sum := @Sum + Arr.I |
Sum := @Sum + Arr.I |
||
end |
end |
||
{Show @Sum}</ |
{Show @Sum}</syntaxhighlight> |
||
=={{header|PARI/GP}}== |
=={{header|PARI/GP}}== |
||
These are built in to GP: <code>vecsum</code> and <code>factorback</code> (the latter can also take factorization matrices, thus the name). They could be coded like so: |
|||
<lang parigp>vecsum(v)={ |
|||
<syntaxhighlight lang="parigp">vecsum1(v)={ |
|||
sum(i=1,#v,v[i]) |
sum(i=1,#v,v[i]) |
||
}; |
}; |
||
vecprod(v)={ |
vecprod(v)={ |
||
prod(i=1,#v,v[i]) |
prod(i=1,#v,v[i]) |
||
};</ |
};</syntaxhighlight> |
||
{{works with|PARI/GP|2.10.0+}} |
|||
In 2.10.0 the function <code>vecprod</code> was introduced as well. Like <code>factorback</code> it gives the product of the elements of an array but unlike <code>factorback</code> it doesn't handle factorization matrices. |
|||
=={{header|Pascal}}== |
=={{header|Pascal}}== |
||
Line 1,282: | Line 2,663: | ||
=={{header|Perl}}== |
=={{header|Perl}}== |
||
< |
<syntaxhighlight lang="perl">my @list = ( 1, 2, 3 ); |
||
my ( $sum, $prod ) = ( 0, 1 ); |
my ( $sum, $prod ) = ( 0, 1 ); |
||
$sum += $_ foreach @list; |
$sum += $_ foreach @list; |
||
$prod *= $_ foreach @list;</ |
$prod *= $_ foreach @list;</syntaxhighlight> |
||
Or using the [https://metacpan.org/pod/List::Util List::Util] module: |
|||
Alternate: |
|||
<syntaxhighlight lang="perl">use List::Util qw/sum0 product/; |
|||
{{libheader|List::Util}} |
|||
my @list = (1..9); |
|||
<lang perl>use List::Util qw( sum reduce ); |
|||
my @list = ( 1, 2, 3 ); |
|||
say "Sum: ", sum0(@list); # sum0 returns 0 for an empty list |
|||
say "Product: ", product(@list);</syntaxhighlight> |
|||
my $sum2 = reduce { $a + $b } 0, @list; |
|||
{{out}} |
|||
my $product = reduce { $a * $b } 1, @list;</lang> |
|||
<pre>Sum: 45 |
|||
Product: 362880</pre> |
|||
=={{header| |
=={{header|Phix}}== |
||
{{libheader|Phix/basics}} |
|||
<lang perl6>my @ary = 1, 5, 10, 100; |
|||
<!--<syntaxhighlight lang="phix">--> |
|||
say 'Sum: ', [+] @ary; |
|||
<span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">3</span><span style="color: #0000FF;">,</span><span style="color: #000000;">4</span><span style="color: #0000FF;">,</span><span style="color: #000000;">5</span><span style="color: #0000FF;">}</span> |
|||
say 'Product: ', [*] @ary;</lang> |
|||
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"sum is %d\n"</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">sum</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">))</span> |
|||
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"prod is %d\n"</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">product</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">))</span> |
|||
<!--</syntaxhighlight>--> |
|||
{{out}} |
|||
<pre> |
|||
sum is 15 |
|||
prod is 120 |
|||
</pre> |
|||
=={{header|Phixmonti}}== |
|||
<syntaxhighlight lang="phixmonti">include ..\Utilitys.pmt |
|||
( 1 2 3 4 5 ) |
|||
dup sum "sum is " print print nl |
|||
1 swap |
|||
len for |
|||
get rot * swap |
|||
endfor |
|||
drop |
|||
"mult is " print print nl</syntaxhighlight> |
|||
=={{header|PHP}}== |
=={{header|PHP}}== |
||
< |
<syntaxhighlight lang="php">$array = array(1,2,3,4,5,6,7,8,9); |
||
echo array_sum($array); |
echo array_sum($array); |
||
echo array_product($array);</ |
echo array_product($array);</syntaxhighlight> |
||
=={{header|Picat}}== |
|||
<syntaxhighlight lang="picat">go => |
|||
L = 1..10, |
|||
println(sum=sum(L)), |
|||
println(prod=prod(L)), |
|||
nl, |
|||
println(sum_reduce=reduce(+,L)), |
|||
println(prod_reduce=reduce(*,L)), |
|||
println(sum_reduce=reduce(+,L,0)), |
|||
println(prod_reduce=reduce(*,L,1)), |
|||
nl, |
|||
println(sum_fold=fold(+,0,L)), |
|||
println(prod_fold=fold(*,1,L)), |
|||
nl, |
|||
println(sum_rec=sum_rec(L)), |
|||
println(prod_rec=prod_rec(L)), |
|||
nl. |
|||
% recursive variants |
|||
sum_rec(List) = Sum => |
|||
sum_rec(List,0,Sum). |
|||
sum_rec([],Sum0,Sum) => |
|||
Sum=Sum0. |
|||
sum_rec([H|T], Sum0,Sum) => |
|||
sum_rec(T, H+Sum0,Sum). |
|||
prod_rec(List) = Prod => |
|||
prod_rec(List,1,Prod). |
|||
prod_rec([],Prod0,Prod) => |
|||
Prod=Prod0. |
|||
prod_rec([H|T], Prod0,Prod) => |
|||
prod_rec(T, H*Prod0,Prod).</syntaxhighlight> |
|||
{{out}} |
|||
<pre>sum = 55 |
|||
prod = 3628800 |
|||
sum_reduce = 55 |
|||
prod_reduce = 3628800 |
|||
sum_reduce = 55 |
|||
prod_reduce = 3628800 |
|||
sum_fold = 55 |
|||
prod_fold = 3628800 |
|||
sum_rec = 55 |
|||
prod_rec = 3628800</pre> |
|||
=={{header|PicoLisp}}== |
=={{header|PicoLisp}}== |
||
< |
<syntaxhighlight lang="picolisp">(let Data (1 2 3 4 5) |
||
(cons |
(cons |
||
(apply + Data) |
(apply + Data) |
||
(apply * Data) ) )</ |
(apply * Data) ) )</syntaxhighlight> |
||
{{Out}} |
|||
Output: |
|||
<pre>(15 . 120)</pre> |
<pre>(15 . 120)</pre> |
||
=={{header|PL/I}}== |
=={{header|PL/I}}== |
||
< |
<syntaxhighlight lang="pli">declare A(10) fixed binary static initial |
||
(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); |
(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); |
||
put skip list (sum(A)); |
put skip list (sum(A)); |
||
put skip list (prod(A));</ |
put skip list (prod(A));</syntaxhighlight> |
||
=={{header|Plain English}}== |
|||
<syntaxhighlight lang="plainenglish">An element is a thing with a number. |
|||
To find a sum and a product of some elements: |
|||
Put 0 into the sum. |
|||
Put 1 into the product. |
|||
Get an element from the elements. |
|||
Loop. |
|||
If the element is nil, exit. |
|||
Add the element's number to the sum. |
|||
Multiply the product by the element's number. |
|||
Put the element's next into the element. |
|||
Repeat. |
|||
To make some example elements: |
|||
If a counter is past 10, exit. |
|||
Allocate memory for an element. |
|||
Put the counter into the element's number. |
|||
Append the element to the example. |
|||
Repeat. |
|||
A product is a number. |
|||
To run: |
|||
Start up. |
|||
Make some example elements. |
|||
Find a sum and a product of the example elements. |
|||
Destroy the example elements. |
|||
Write "Sum: " then the sum on the console. |
|||
Write "Product: " then the product on the console. |
|||
Wait for the escape key. |
|||
Shut down. |
|||
A sum is a number.</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
Sum: 55 |
|||
Product: 3628800 |
|||
</pre> |
|||
=={{header|Pop11}}== |
=={{header|Pop11}}== |
||
Simple loop: |
Simple loop: |
||
< |
<syntaxhighlight lang="pop11">lvars i, sum = 0, prod = 1, 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; |
||
ar(i) * prod -> prod; |
ar(i) * prod -> prod; |
||
endfor;</ |
endfor;</syntaxhighlight> |
||
One can alternatively use second order iterator: |
One can alternatively use second order iterator: |
||
< |
<syntaxhighlight lang="pop11">lvars sum = 0, prod = 1, 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); |
||
appdata(ar, procedure(x); x * prod -> prod; endprocedure);</ |
appdata(ar, procedure(x); x * prod -> prod; endprocedure);</syntaxhighlight> |
||
=={{header|PostScript}}== |
|||
<syntaxhighlight lang="text"> |
|||
/sumandproduct |
|||
{ |
|||
/x exch def |
|||
/sum 0 def |
|||
/prod 0 def |
|||
/i 0 def |
|||
x length 0 eq |
|||
{ |
|||
} |
|||
{ |
|||
/prod prod 1 add def |
|||
x length{ |
|||
/sum sum x i get add def |
|||
/prod prod x i get mul def |
|||
/i i 1 add def |
|||
}repeat |
|||
}ifelse |
|||
sum == |
|||
prod == |
|||
}def |
|||
</syntaxhighlight> |
|||
{{libheader|initlib}} |
|||
<syntaxhighlight lang="postscript"> |
|||
% sum |
|||
[1 1 1 1 1] 0 {add} fold |
|||
% product |
|||
[1 1 1 1 1] 1 {mul} fold |
|||
</syntaxhighlight> |
|||
=={{header|PowerShell}}== |
=={{header|PowerShell}}== |
||
The <code>Measure-Object</code> cmdlet already knows how to compute a sum: |
The <code>Measure-Object</code> cmdlet already knows how to compute a sum: |
||
< |
<syntaxhighlight lang="powershell">function Get-Sum ($a) { |
||
return ($a | Measure-Object -Sum).Sum |
return ($a | Measure-Object -Sum).Sum |
||
}</ |
}</syntaxhighlight> |
||
But not how to compute a product: |
But not how to compute a product: |
||
< |
<syntaxhighlight lang="powershell">function Get-Product ($a) { |
||
if ($a.Length -eq 0) { |
if ($a.Length -eq 0) { |
||
return 0 |
return 0 |
||
Line 1,348: | Line 2,877: | ||
return $p |
return $p |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
One could also let PowerShell do all the work by simply creating an expression to evaluate: |
One could also let PowerShell do all the work by simply creating an expression to evaluate: |
||
{{works with|PowerShell|2}} |
{{works with|PowerShell|2}} |
||
< |
<syntaxhighlight lang="powershell">function Get-Product ($a) { |
||
if ($a.Length -eq 0) { |
if ($a.Length -eq 0) { |
||
return 0 |
return 0 |
||
Line 1,358: | Line 2,887: | ||
$s = $a -join '*' |
$s = $a -join '*' |
||
return (Invoke-Expression $s) |
return (Invoke-Expression $s) |
||
}</ |
}</syntaxhighlight> |
||
Even nicer, however, is a function which computes both at once and returns a custom object with appropriate properties: |
Even nicer, however, is a function which computes both at once and returns a custom object with appropriate properties: |
||
< |
<syntaxhighlight lang="powershell">function Get-SumAndProduct ($a) { |
||
$sum = 0 |
$sum = 0 |
||
if ($a.Length -eq 0) { |
if ($a.Length -eq 0) { |
||
Line 1,375: | Line 2,904: | ||
$ret | Add-Member NoteProperty Product $prod |
$ret | Add-Member NoteProperty Product $prod |
||
return $ret |
return $ret |
||
}</ |
}</syntaxhighlight> |
||
{{Out}} |
|||
Output: |
|||
<pre>PS> Get-SumAndProduct 5,9,7,2,3,8,4 |
<pre>PS> Get-SumAndProduct 5,9,7,2,3,8,4 |
||
Line 1,384: | Line 2,913: | ||
=={{header|Prolog}}== |
=={{header|Prolog}}== |
||
< |
<syntaxhighlight lang="prolog">sum([],0). |
||
sum([H|T],X) :- sum(T,Y), X is H + Y. |
sum([H|T],X) :- sum(T,Y), X is H + Y. |
||
product([],1). |
product([],1). |
||
product([H|T],X) :- product(T,Y), X is H * X.</ |
product([H|T],X) :- product(T,Y), X is H * X.</syntaxhighlight> |
||
test |
test |
||
Line 1,397: | Line 2,926: | ||
Using fold |
Using fold |
||
< |
<syntaxhighlight lang="prolog"> |
||
add(A,B,R):- |
add(A,B,R):- |
||
R is A + B. |
R is A + B. |
||
Line 1,421: | Line 2,950: | ||
Prod = 24 . |
Prod = 24 . |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|PostScript}}== |
|||
<lang> |
|||
/sumandproduct |
|||
{ |
|||
/x exch def |
|||
/sum 0 def |
|||
/prod 0 def |
|||
/i 0 def |
|||
x length 0 eq |
|||
{ |
|||
} |
|||
{ |
|||
/prod prod 1 add def |
|||
x length{ |
|||
/sum sum x i get add def |
|||
/prod prod x i get mul def |
|||
/i i 1 add def |
|||
}repeat |
|||
}ifelse |
|||
sum == |
|||
prod == |
|||
}def |
|||
</lang> |
|||
{{libheader|initlib}} |
|||
<lang postscript> |
|||
% sum |
|||
[1 1 1 1 1] 0 {add} fold |
|||
% product |
|||
[1 1 1 1 1] 1 {mul} fold |
|||
</lang> |
|||
=={{header|PureBasic}}== |
=={{header|PureBasic}}== |
||
< |
<syntaxhighlight lang="purebasic">Dim MyArray(9) |
||
Define a, sum=0, prod=1 |
Define a, sum=0, prod=1 |
||
Line 1,470: | Line 2,966: | ||
Debug "The sum is " + Str(sum) ; Present the results |
Debug "The sum is " + Str(sum) ; Present the results |
||
Debug "Product is " + Str(prod)</ |
Debug "Product is " + Str(prod)</syntaxhighlight> |
||
=={{header|Python}}== |
=={{header|Python}}== |
||
{{works with|Python|2.5}} |
{{works with|Python|2.5}} |
||
< |
<syntaxhighlight lang="python">numbers = [1, 2, 3] |
||
total = sum(numbers) |
total = sum(numbers) |
||
product = 1 |
product = 1 |
||
for i in numbers: |
for i in numbers: |
||
product *= i</ |
product *= i</syntaxhighlight> |
||
Or functionally (faster but perhaps less clear): |
Or functionally (faster but perhaps less clear): |
||
{{works with|Python|2.5}} |
{{works with|Python|2.5}} |
||
< |
<syntaxhighlight lang="python">from operator import mul, add |
||
sum = reduce(add, numbers) # note: this version doesn't work with empty lists |
sum = reduce(add, numbers) # note: this version doesn't work with empty lists |
||
sum = reduce(add, numbers, 0) |
sum = reduce(add, numbers, 0) |
||
product = reduce(mul, numbers) # note: this version doesn't work with empty lists |
product = reduce(mul, numbers) # note: this version doesn't work with empty lists |
||
product = reduce(mul, numbers, 1)</ |
product = reduce(mul, numbers, 1)</syntaxhighlight> |
||
{{libheader| |
{{libheader|NumPy}} |
||
< |
<syntaxhighlight lang="python">from numpy import r_ |
||
numbers = r_[1:4] |
numbers = r_[1:4] |
||
total = numbers.sum() |
total = numbers.sum() |
||
product = numbers.prod()</ |
product = numbers.prod()</syntaxhighlight> |
||
If you are summing floats in Python 2.6+, you should use <tt>math.fsum()</tt> to avoid loss of precision: |
If you are summing floats in Python 2.6+, you should use <tt>math.fsum()</tt> to avoid loss of precision: |
||
{{works with|Python|2.6, 3.x}} |
{{works with|Python|2.6, 3.x}} |
||
< |
<syntaxhighlight lang="python">import math |
||
total = math.fsum(floats)</ |
total = math.fsum(floats)</syntaxhighlight> |
||
=={{header|QBasic}}== |
|||
{{works with|QBasic}} |
|||
{{works with|QuickBasic}} |
|||
{{works with|True BASIC}} |
|||
<syntaxhighlight lang="qbasic">DIM array(1 TO 5) |
|||
DATA 1, 2, 3, 4, 5 |
|||
FOR index = LBOUND(array) TO UBOUND(array) |
|||
READ array(index) |
|||
NEXT index |
|||
LET sum = 0 |
|||
LET prod = 1 |
|||
FOR index = LBOUND(array) TO UBOUND(array) |
|||
LET sum = sum + array(index) |
|||
LET prod = prod * array(index) |
|||
NEXT index |
|||
PRINT "The sum is "; sum |
|||
PRINT "and the product is "; prod |
|||
END</syntaxhighlight> |
|||
=={{header|Quackery}}== |
|||
<syntaxhighlight lang="quackery">[ 0 swap witheach + ] is sum ( [ --> n ) |
|||
[ 1 swap witheach * ] is product ( [ --> n )</syntaxhighlight> |
|||
In the shell (i.e. Quackery REPL): |
|||
<syntaxhighlight lang="quackery"> |
|||
/O> ' [ 1 2 3 4 5 ] sum echo cr |
|||
... ' [ 1 2 3 4 5 ] product echo |
|||
... |
|||
15 |
|||
120 |
|||
Stack empty.</syntaxhighlight> |
|||
=={{header|R}}== |
=={{header|R}}== |
||
< |
<syntaxhighlight lang="r">total <- sum(1:5) |
||
product <- prod(1:5)</ |
product <- prod(1:5)</syntaxhighlight> |
||
=={{header|Racket}}== |
=={{header|Racket}}== |
||
< |
<syntaxhighlight lang="racket">#lang racket |
||
#lang racket |
|||
(for/sum ([x #(3 1 4 1 5 9)]) x) |
(for/sum ([x #(3 1 4 1 5 9)]) x) |
||
(for/product ([x #(3 1 4 1 5 9)]) x) |
(for/product ([x #(3 1 4 1 5 9)]) x)</syntaxhighlight> |
||
</lang> |
|||
=={{header|Raku}}== |
|||
(formerly Perl 6) |
|||
<syntaxhighlight lang="raku" line>my @ary = 1, 5, 10, 100; |
|||
say 'Sum: ', [+] @ary; |
|||
say 'Product: ', [*] @ary;</syntaxhighlight> |
|||
=={{header|Rapira}}== |
|||
<syntaxhighlight lang="rapira">fun sumOfArr(arr) |
|||
sum := 0 |
|||
for N from 1 to #arr do |
|||
sum := sum + arr[N] |
|||
od |
|||
return sum |
|||
end |
|||
fun productOfArr(arr) |
|||
product := arr[1] |
|||
for N from 2 to #arr do |
|||
product := product * arr[N] |
|||
od |
|||
return product |
|||
end</syntaxhighlight> |
|||
=={{header|Raven}}== |
=={{header|Raven}}== |
||
< |
<syntaxhighlight lang="raven">0 [ 1 2 3 ] each + |
||
1 [ 1 2 3 ] each *</ |
1 [ 1 2 3 ] each *</syntaxhighlight> |
||
=={{header|REBOL}}== |
=={{header|REBOL}}== |
||
< |
<syntaxhighlight lang="rebol">REBOL [ |
||
Title: "Sum and Product" |
Title: "Sum and Product" |
||
Date: 2010-01-04 |
|||
Author: oofoe |
|||
URL: http://rosettacode.org/wiki/Sum_and_product_of_array |
URL: http://rosettacode.org/wiki/Sum_and_product_of_array |
||
] |
] |
||
Line 1,552: | Line 3,101: | ||
print [crlf "Fancy reducing function:"] |
print [crlf "Fancy reducing function:"] |
||
assert [55 = rsum [1 2 3 4 5 6 7 8 9 10]] |
assert [55 = rsum [1 2 3 4 5 6 7 8 9 10]] |
||
assert [3628800 = rproduct [1 2 3 4 5 6 7 8 9 10]]</ |
assert [3628800 = rproduct [1 2 3 4 5 6 7 8 9 10]]</syntaxhighlight> |
||
Output: |
|||
{{Out}} |
|||
<pre>Simple dedicated functions: |
<pre>Simple dedicated functions: |
||
ok [55 = sum [1 2 3 4 5 6 7 8 9 10]] |
ok [55 = sum [1 2 3 4 5 6 7 8 9 10]] |
||
Line 1,563: | Line 3,111: | ||
ok [55 = rsum [1 2 3 4 5 6 7 8 9 10]] |
ok [55 = rsum [1 2 3 4 5 6 7 8 9 10]] |
||
ok [3628800 = rproduct [1 2 3 4 5 6 7 8 9 10]]</pre> |
ok [3628800 = rproduct [1 2 3 4 5 6 7 8 9 10]]</pre> |
||
=={{header|Red}}== |
|||
<syntaxhighlight lang="rebol">Red [ |
|||
red-version: 0.6.4 |
|||
description: "Find the sum and product of an array of numbers." |
|||
] |
|||
product: function [ |
|||
"Returns the product of all values in a block." |
|||
values [any-list! vector!] |
|||
][ |
|||
result: 1 |
|||
foreach value values [result: result * value] |
|||
result |
|||
] |
|||
a: [1 2 3 4 5 6 7 8 9 10] |
|||
print a |
|||
print ["Sum:" sum a] |
|||
print ["Product:" product a]</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
1 2 3 4 5 6 7 8 9 10 |
|||
Sum: 55 |
|||
Product: 3628800 |
|||
</pre> |
|||
=={{header|REXX}}== |
=={{header|REXX}}== |
||
< |
<syntaxhighlight lang="rexx">/*REXX program adds and multiplies N elements of a (populated) array @. */ |
||
numeric digits |
numeric digits 200 /*200 decimal digit #s (default is 9).*/ |
||
parse arg N .; if N=='' then N=20 /*Not specified? Then use the default.*/ |
|||
do j=1 for m /*build an array of twenty elements. */ |
|||
do j=1 for N /*build array of N elements (or 20?).*/ |
|||
@.j=j /*set 1st to 1, 3rd to 3, 8th to 8 ··· */ |
|||
end /*j*/ |
end /*j*/ |
||
sum=0 |
sum=0 /*initialize SUM (variable) to zero. */ |
||
prod=1 |
prod=1 /*initialize PROD (variable) to unity.*/ |
||
do k=1 for |
do k=1 for N |
||
sum =sum + |
sum = sum + @.k /*add the element to the running total.*/ |
||
prod=prod* |
prod = prod * @.k /*multiply element to running product. */ |
||
end /*k*/ |
end /*k*/ /* [↑] this pgm: same as N factorial.*/ |
||
say ' sum of' m "elements for the |
say ' sum of ' m " elements for the @ array is: " sum |
||
say 'product of' m "elements for the |
say ' product of ' m " elements for the @ array is: " prod |
||
/*stick a fork in it, we're done. |
/*stick a fork in it, we're all done. */</syntaxhighlight> |
||
'''output''' using the default input of: <tt> 20 </tt> |
|||
'''output''' |
|||
<pre> |
<pre> |
||
sum of |
sum of M elements for the @ array is: 210 |
||
product of |
product of M elements for the @ array is: 2432902008176640000 |
||
</pre> |
|||
=={{header|Ring}}== |
|||
<syntaxhighlight lang="ring"> |
|||
aList = 1:10 nSum=0 nProduct=0 |
|||
for x in aList nSum += x nProduct *= x next |
|||
See "Sum = " + nSum + nl |
|||
See "Product = " + nProduct + nl |
|||
</syntaxhighlight> |
|||
=={{header|RPL}}== |
|||
{{works with|Halcyon Calc|4.2.7}} |
|||
≪ DUP |
|||
DUP 1 CON DOT |
|||
SWAP ARRY→ LIST→ SWAP 1 - START * NEXT |
|||
≫ |
|||
'SUMPR' STO |
|||
[ 2 4 8 -5 ] SUMPR |
|||
{{out}} |
|||
<pre> |
|||
2: 9 |
|||
1: -320 |
|||
</pre> |
</pre> |
||
=={{header|Ruby}}== |
=={{header|Ruby}}== |
||
< |
<syntaxhighlight lang="ruby">arr = [1,2,3,4,5] # or ary = *1..5, or ary = (1..5).to_a |
||
p sum = arr.inject(0) { |sum, item| sum + item } |
p sum = arr.inject(0) { |sum, item| sum + item } |
||
# => 15 |
# => 15 |
||
p product = arr.inject(1) { |prod, element| prod * element } |
p product = arr.inject(1) { |prod, element| prod * element } |
||
# => 120</ |
# => 120</syntaxhighlight> |
||
{{works with|Ruby|1.8.7}} |
{{works with|Ruby|1.8.7}} |
||
< |
<syntaxhighlight lang="ruby">arr = [1,2,3,4,5] |
||
p sum = arr.inject(0, :+) #=> 15 |
p sum = arr.inject(0, :+) #=> 15 |
||
p product = arr.inject(1, :*) #=> 120 |
p product = arr.inject(1, :*) #=> 120 |
||
Line 1,602: | Line 3,200: | ||
# then the first element of collection is used as the initial value of memo. |
# then the first element of collection is used as the initial value of memo. |
||
p sum = arr.inject(:+) #=> 15 |
p sum = arr.inject(:+) #=> 15 |
||
p product = arr.inject(:*) #=> 120</ |
p product = arr.inject(:*) #=> 120</syntaxhighlight> |
||
Note: When the Array is empty, the initial value returns. However, nil returns if not giving an initial value. |
|||
<syntaxhighlight lang="ruby">arr = [] |
|||
p arr.inject(0, :+) #=> 0 |
|||
p arr.inject(1, :*) #=> 1 |
|||
p arr.inject(:+) #=> nil |
|||
p arr.inject(:*) #=> nil</syntaxhighlight> |
|||
Enumerable#reduce is the alias of Enumerable#inject. |
|||
{{works with|Ruby|1.9.3}} |
|||
<syntaxhighlight lang="ruby">arr = [1,2,3,4,5] |
|||
p sum = arr.sum #=> 15 |
|||
p [].sum #=> 0</syntaxhighlight> |
|||
=={{header|Run BASIC}}== |
=={{header|Run BASIC}}== |
||
< |
<syntaxhighlight lang="runbasic">dim array(100) |
||
for i = 1 To 100 |
for i = 1 To 100 |
||
array(i) = rnd(0) * 100 |
array(i) = rnd(0) * 100 |
||
Line 1,617: | Line 3,229: | ||
Print " Sum is ";sum |
Print " Sum is ";sum |
||
Print "Product is ";product</ |
Print "Product is ";product</syntaxhighlight> |
||
=={{header|Rust}}== |
=={{header|Rust}}== |
||
<syntaxhighlight lang="rust"> |
|||
<lang rust>use std::iter::{AdditiveIterator, MultiplicativeIterator}; |
|||
fn main() { |
fn main() { |
||
let arr = [ |
let arr = vec![1, 2, 3, 4, 5, 6, 7, 8, 9]; |
||
// using fold |
// using fold |
||
let sum = arr.iter().fold( |
let sum = arr.iter().fold(0i32, |a, &b| a + b); |
||
let product = arr.iter().fold( |
let product = arr.iter().fold(1i32, |a, &b| a * b); |
||
println!("the sum is { |
println!("the sum is {} and the product is {}", sum, product); |
||
// or using sum and product |
// or using sum and product |
||
let sum = arr.iter().sum::<i32>(); |
|||
// and MultiplicativeIterator |
|||
let |
let product = arr.iter().product::<i32>(); |
||
println!("the sum is {} and the product is {}", sum, product); |
|||
let product2 = arr.iter().map(|&a| a).product(); |
|||
} |
|||
println!("the sum is {:d} and the product is {:d}", sum2, product2); |
|||
</syntaxhighlight> |
|||
}</lang> |
|||
=={{header|S-lang}}== |
|||
<syntaxhighlight lang="s-lang">variable a = [5, -2, 3, 4, 666, 7];</syntaxhighlight> |
|||
The sum of array elements is handled by an intrinsic. |
|||
[note: print is slsh-specific; if not available, use printf().] |
|||
<syntaxhighlight lang="s-lang">print(sum(a));</syntaxhighlight> |
|||
The product is slightly more involved; I'll use this as a |
|||
chance to show the alternate stack-based use of 'foreach': |
|||
<syntaxhighlight lang="s-lang">variable prod = a[0]; |
|||
% Skipping the loop variable causes the val to be placed on the stack. |
|||
% Also note that the double-brackets ARE required. The inner one creates |
|||
% a "range array" based on the length of a. |
|||
foreach (a[[1:]]) |
|||
% () pops it off. |
|||
prod *= (); |
|||
print(prod);</syntaxhighlight> |
|||
=={{header|SAS}}== |
=={{header|SAS}}== |
||
< |
<syntaxhighlight lang="sas">data _null_; |
||
array a{*} a1-a100; |
array a{*} a1-a100; |
||
do i=1 to 100; |
do i=1 to 100; |
||
Line 1,645: | Line 3,278: | ||
b=sum(of a{*}); |
b=sum(of a{*}); |
||
put b c; |
put b c; |
||
run;</ |
run;</syntaxhighlight> |
||
=={{header|Sather}}== |
=={{header|Sather}}== |
||
< |
<syntaxhighlight lang="sather">class MAIN is |
||
main is |
main is |
||
a :ARRAY{INT} := |10, 5, 5, 20, 60, 100|; |
a :ARRAY{INT} := |10, 5, 5, 20, 60, 100|; |
||
Line 1,657: | Line 3,290: | ||
#OUT + sum + " " + prod + "\n"; |
#OUT + sum + " " + prod + "\n"; |
||
end; |
end; |
||
end;</ |
end;</syntaxhighlight> |
||
=={{header|Scala}}== |
=={{header|Scala}}== |
||
< |
<syntaxhighlight lang="scala">val seq = Seq(1, 2, 3, 4, 5) |
||
val sum = seq.foldLeft(0)(_ + _) |
val sum = seq.foldLeft(0)(_ + _) |
||
val product = seq.foldLeft(1)(_ * _)</ |
val product = seq.foldLeft(1)(_ * _)</syntaxhighlight> |
||
Or even shorter: |
Or even shorter: |
||
< |
<syntaxhighlight lang="scala">val sum = seq.sum |
||
val product = seq.product</ |
val product = seq.product</syntaxhighlight> |
||
Works with all data types for which a Numeric implicit is available. |
Works with all data types for which a Numeric implicit is available. |
||
=={{header|Scheme}}== |
=={{header|Scheme}}== |
||
< |
<syntaxhighlight lang="scheme">(apply + '(1 2 3 4 5)) |
||
(apply * '(1 2 3 4 5))</ |
(apply * '(1 2 3 4 5))</syntaxhighlight> |
||
A tail-recursive solution, without the n-ary operator "trick". Because Scheme supports tail call optimization, this is as space-efficient as an imperative loop. |
A tail-recursive solution, without the n-ary operator "trick". Because Scheme supports tail call optimization, this is as space-efficient as an imperative loop. |
||
< |
<syntaxhighlight lang="scheme">(define (reduce f i l) |
||
(if (null? l) |
(if (null? l) |
||
i |
i |
||
Line 1,680: | Line 3,313: | ||
(reduce + 0 '(1 2 3 4 5)) ;; 0 is unit for + |
(reduce + 0 '(1 2 3 4 5)) ;; 0 is unit for + |
||
(reduce * 1 '(1 2 3 4 5)) ;; 1 is unit for *</ |
(reduce * 1 '(1 2 3 4 5)) ;; 1 is unit for *</syntaxhighlight> |
||
=={{header|Seed7}}== |
=={{header|Seed7}}== |
||
< |
<syntaxhighlight lang="seed7">const func integer: sumArray (in array integer: valueArray) is func |
||
result |
result |
||
var integer: sum is 0; |
var integer: sum is 0; |
||
Line 1,702: | Line 3,336: | ||
prod *:= value; |
prod *:= value; |
||
end for; |
end for; |
||
end func;</ |
end func;</syntaxhighlight> |
||
Call these functions with: |
Call these functions with: |
||
writeln(sumArray([](1, 2, 3, 4, 5))); |
writeln(sumArray([](1, 2, 3, 4, 5))); |
||
Line 1,708: | Line 3,342: | ||
=={{header|SETL}}== |
=={{header|SETL}}== |
||
< |
<syntaxhighlight lang="setl">numbers := [1 2 3 4 5 6 7 8 9]; |
||
print(+/ numbers, */ numbers);</ |
print(+/ numbers, */ numbers);</syntaxhighlight> |
||
=> <code>45 362880</code> |
=> <code>45 362880</code> |
||
=={{header|Sidef}}== |
|||
Using built-in methods: |
|||
<syntaxhighlight lang="ruby">var ary = [1, 2, 3, 4, 5]; |
|||
say ary.sum; # => 15 |
|||
say ary.prod; # => 120</syntaxhighlight> |
|||
Alternatively, using hyper-operators: |
|||
<syntaxhighlight lang="ruby">var ary = [1, 2, 3, 4, 5]; |
|||
say ary«+»; # => 15 |
|||
say ary«*»; # => 120</syntaxhighlight> |
|||
=={{header|Slate}}== |
=={{header|Slate}}== |
||
< |
<syntaxhighlight lang="slate">#(1 2 3 4 5) reduce: [:sum :number | sum + number] |
||
#(1 2 3 4 5) reduce: [:product :number | product * number]</ |
#(1 2 3 4 5) reduce: [:product :number | product * number]</syntaxhighlight> |
||
Shorthand for the above with a macro: |
Shorthand for the above with a macro: |
||
< |
<syntaxhighlight lang="slate">#(1 2 3 4 5) reduce: #+ `er |
||
#(1 2 3 4 5) reduce: #* `er</ |
#(1 2 3 4 5) reduce: #* `er</syntaxhighlight> |
||
=={{header|Smalltalk}}== |
=={{header|Smalltalk}}== |
||
< |
<syntaxhighlight lang="smalltalk">#(1 2 3 4 5) inject: 0 into: [:sum :number | sum + number] |
||
#(1 2 3 4 5) inject: 1 into: [:product :number | product * number]</ |
#(1 2 3 4 5) inject: 1 into: [:product :number | product * number]</syntaxhighlight> |
||
Some implementation also provide a ''fold:'' message: |
Some implementation also provide a ''fold:'' message: |
||
< |
<syntaxhighlight lang="smalltalk">#(1 2 3 4 5) fold: [:sum :number | sum + number] |
||
#(1 2 3 4 5) fold: [:product :number | product * number]</ |
#(1 2 3 4 5) fold: [:product :number | product * number]</syntaxhighlight> |
||
=={{header|SNOBOL4}}== |
=={{header|SNOBOL4}}== |
||
< |
<syntaxhighlight lang="snobol"> t = table() |
||
* read the integer from the std. input |
* read the integer from the std. input |
||
init_tab t<x = x + 1> = trim(input) :s(init_tab) |
init_tab t<x = x + 1> = trim(input) :s(init_tab) |
||
Line 1,738: | Line 3,385: | ||
out output = "Sum: " sum |
out output = "Sum: " sum |
||
output = "Prod: " product |
output = "Prod: " product |
||
end</ |
end</syntaxhighlight> |
||
Input |
Input |
||
Line 1,746: | Line 3,393: | ||
4 |
4 |
||
5 |
5 |
||
{{Out}} |
|||
Output |
|||
<pre> |
|||
Sum: 15 |
Sum: 15 |
||
Prod: 120 |
Prod: 120 |
||
</pre> |
|||
=={{header|SparForte}}== |
|||
As a structured script. |
|||
<syntaxhighlight lang="ada">#!/usr/local/bin/spar |
|||
pragma annotate( summary, "arraysum" ) |
|||
@( description, "Compute the sum and product of an array of integers." ) |
|||
@( see_also, "http://rosettacode.org/wiki/Sum_and_product_of_an_array" ) |
|||
@( author, "Ken O. Burtch" ); |
|||
pragma license( unrestricted ); |
|||
pragma restriction( no_external_commands ); |
|||
procedure arraysum is |
|||
type int_array is array(1..10) of integer; |
|||
myarr : int_array := (1,2,3,4,5,6,7,8,9,10 ); |
|||
begin |
|||
? stats.sum( myarr ); |
|||
declare |
|||
product : integer := 1; |
|||
begin |
|||
for i in arrays.first( myarr )..arrays.last( myarr ) loop |
|||
product := @ * myarr(i); |
|||
end loop; |
|||
? product; |
|||
end; |
|||
end arraysum;</syntaxhighlight> |
|||
=={{header|Sparkling}}== |
|||
<syntaxhighlight lang="sparkling">spn:1> reduce({ 1, 2, 3, 4, 5 }, 0, function(x, y) { return x + y; }) |
|||
= 15 |
|||
spn:2> reduce({ 1, 2, 3, 4, 5 }, 1, function(x, y) { return x * y; }) |
|||
= 120</syntaxhighlight> |
|||
=={{header|Standard ML}}== |
=={{header|Standard ML}}== |
||
===Arrays=== |
===Arrays=== |
||
< |
<syntaxhighlight lang="sml">(* ints *) |
||
val a = Array.fromList [1, 2, 3, 4, 5]; |
val a = Array.fromList [1, 2, 3, 4, 5]; |
||
Array.foldl op+ 0 a; |
Array.foldl op+ 0 a; |
||
Line 1,759: | Line 3,440: | ||
val a = Array.fromList [1.0, 2.0, 3.0, 4.0, 5.0]; |
val a = Array.fromList [1.0, 2.0, 3.0, 4.0, 5.0]; |
||
Array.foldl op+ 0.0 a; |
Array.foldl op+ 0.0 a; |
||
Array.foldl op* 1.0 a;</ |
Array.foldl op* 1.0 a;</syntaxhighlight> |
||
===Lists=== |
===Lists=== |
||
< |
<syntaxhighlight lang="sml">(* ints *) |
||
val x = [1, 2, 3, 4, 5]; |
val x = [1, 2, 3, 4, 5]; |
||
foldl op+ 0 x; |
foldl op+ 0 x; |
||
Line 1,768: | Line 3,449: | ||
val x = [1.0, 2.0, 3.0, 4.0, 5.0]; |
val x = [1.0, 2.0, 3.0, 4.0, 5.0]; |
||
foldl op+ 0.0 x; |
foldl op+ 0.0 x; |
||
foldl op* 1.0 x;</ |
foldl op* 1.0 x;</syntaxhighlight> |
||
=={{header|Stata}}== |
|||
Mata does not have a builtin product function, but one can do the following, which will compute the product of nonzero elements of the array: |
|||
<syntaxhighlight lang="stata">a = 1,-2,-3,-4,5 |
|||
sum(a) |
|||
-3 |
|||
(-1)^mod(sum(a:<0),2)*exp(sum(log(abs(a)))) |
|||
-120</syntaxhighlight> |
|||
=={{header|Swift}}== |
=={{header|Swift}}== |
||
< |
<syntaxhighlight lang="swift">let a = [1, 2, 3, 4, 5] |
||
println(a.reduce(0, +)) // prints 15 |
println(a.reduce(0, +)) // prints 15 |
||
println(a.reduce(1, *)) // prints 120 |
println(a.reduce(1, *)) // prints 120 |
||
println(reduce(a, 0, +)) // prints 15 |
println(reduce(a, 0, +)) // prints 15 |
||
println(reduce(a, 1, *)) // prints 120</ |
println(reduce(a, 1, *)) // prints 120</syntaxhighlight> |
||
=={{header|Tcl}}== |
=={{header|Tcl}}== |
||
< |
<syntaxhighlight lang="tcl">set arr [list 3 6 8] |
||
set sum [expr [join $arr +]] |
set sum [expr [join $arr +]] |
||
set prod [expr [join $arr *]]</ |
set prod [expr [join $arr *]]</syntaxhighlight> |
||
{{works with|Tcl|8.5}} |
{{works with|Tcl|8.5}} |
||
< |
<syntaxhighlight lang="tcl">set arr [list 3 6 8] |
||
set sum [tcl::mathop::+ {*}$arr] |
set sum [tcl::mathop::+ {*}$arr] |
||
set prod [tcl::mathop::* {*}$arr]</ |
set prod [tcl::mathop::* {*}$arr]</syntaxhighlight> |
||
=={{header|TI-83 BASIC}}== |
=={{header|TI-83 BASIC}}== |
||
Use the built-in functions < |
Use the built-in functions <code>sum()</code> and <code>prod()</code>. |
||
<syntaxhighlight lang="ti83b">seq(X,X,1,10,1)→L₁ |
|||
{1 2 3 4 5 6 7 8 9 10} |
|||
sum(L₁) |
|||
55 |
|||
prod(L₁) |
|||
3628800</syntaxhighlight> |
|||
=={{header|Toka}}== |
=={{header|Toka}}== |
||
< |
<syntaxhighlight lang="toka">4 cells is-array foo |
||
212 1 foo array.put |
212 1 foo array.put |
||
Line 1,802: | Line 3,498: | ||
( product ) |
( product ) |
||
reset 1 4 0 [ i foo array.get * ] countedLoop .</ |
reset 1 4 0 [ i foo array.get * ] countedLoop .</syntaxhighlight> |
||
=={{header|Trith}}== |
=={{header|Trith}}== |
||
< |
<syntaxhighlight lang="trith">[1 2 3 4 5] 0 [+] foldl</syntaxhighlight> |
||
< |
<syntaxhighlight lang="trith">[1 2 3 4 5] 1 [*] foldl</syntaxhighlight> |
||
=={{header|True BASIC}}== |
|||
{{works with|QBasic}} |
|||
<syntaxhighlight lang="qbasic">DIM array(1 TO 5) |
|||
DATA 1, 2, 3, 4, 5 |
|||
FOR index = LBOUND(array) TO UBOUND(array) |
|||
READ array(index) |
|||
NEXT index |
|||
LET sum = 0 |
|||
LET prod = 1 |
|||
FOR index = LBOUND(array) TO UBOUND(array) |
|||
LET sum = sum + array(index) |
|||
LET prod = prod * array(index) |
|||
NEXT index |
|||
PRINT "The sum is "; sum |
|||
PRINT "and the product is "; prod |
|||
END</syntaxhighlight> |
|||
=={{header|TUSCRIPT}}== |
=={{header|TUSCRIPT}}== |
||
< |
<syntaxhighlight lang="tuscript"> |
||
$$ MODE TUSCRIPT |
$$ MODE TUSCRIPT |
||
list="1'2'3'4'5" |
list="1'2'3'4'5" |
||
Line 1,819: | Line 3,536: | ||
ENDLOOP |
ENDLOOP |
||
PRINT "product: ",product |
PRINT "product: ",product |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{Out}} |
|||
Output: |
|||
<pre> |
<pre> |
||
sum: 15 |
sum: 15 |
||
Line 1,830: | Line 3,547: | ||
From an internal variable, $IFS delimited: |
From an internal variable, $IFS delimited: |
||
< |
<syntaxhighlight lang="bash">sum=0 |
||
prod=1 |
prod=1 |
||
list="1 2 3" |
list="1 2 3" |
||
Line 1,836: | Line 3,553: | ||
do sum="$(($sum + $n))"; prod="$(($prod * $n))" |
do sum="$(($sum + $n))"; prod="$(($prod * $n))" |
||
done |
done |
||
echo $sum $prod</ |
echo $sum $prod</syntaxhighlight> |
||
From the argument list (ARGV): |
From the argument list (ARGV): |
||
< |
<syntaxhighlight lang="bash">sum=0 |
||
prod=1 |
prod=1 |
||
for n |
for n |
||
do sum="$(($sum + $n))"; prod="$(($prod * $n))" |
do sum="$(($sum + $n))"; prod="$(($prod * $n))" |
||
done |
done |
||
echo $sum $prod</ |
echo $sum $prod</syntaxhighlight> |
||
From STDIN, one integer per line: |
From STDIN, one integer per line: |
||
< |
<syntaxhighlight lang="bash">sum=0 |
||
prod=1 |
prod=1 |
||
while read n |
while read n |
||
do sum="$(($sum + $n))"; prod="$(($prod * $n))" |
do sum="$(($sum + $n))"; prod="$(($prod * $n))" |
||
done |
done |
||
echo $sum $prod</ |
echo $sum $prod</syntaxhighlight> |
||
{{works with| |
{{works with|Bourne Again SHell}} |
||
{{works with|Korn Shell}} |
|||
From variable: |
|||
{{works with|Zsh}} |
|||
Using an actual array variable: |
|||
< |
<syntaxhighlight lang="bash">list=(20 20 2); |
||
(( sum=0, prod=1 )) |
|||
for |
for n in "${list[@]}"; do |
||
(( sum += n, prod *= n )) |
|||
done |
done |
||
printf '%d\t%d\n' "$sum" "$prod" |
|||
echo $SUM $PROD</lang> |
|||
</syntaxhighlight> |
|||
{{Out}} |
|||
<pre>42 800</pre> |
|||
=={{header|UnixPipes}}== |
=={{header|UnixPipes}}== |
||
Uses [[ksh93]]-style process substitution. |
Uses [[ksh93]]-style process substitution. |
||
{{works with|bash}} |
{{works with|bash}} |
||
< |
<syntaxhighlight lang="bash">prod() { |
||
(read B; res=$1; test -n "$B" && expr $res \* $B || echo $res) |
(read B; res=$1; test -n "$B" && expr $res \* $B || echo $res) |
||
} |
} |
||
Line 1,883: | Line 3,606: | ||
(echo 3; echo 1; echo 4;echo 1;echo 5;echo 9) | |
(echo 3; echo 1; echo 4;echo 1;echo 5;echo 9) | |
||
tee >(fold sum) >(fold prod) > /dev/null</ |
tee >(fold sum) >(fold prod) > /dev/null</syntaxhighlight> |
||
There is a race between <code>fold sum</code> and <code>fold prod</code>, which run in parallel. The program might print sum before product, or print product before sum. |
There is a race between <code>fold sum</code> and <code>fold prod</code>, which run in parallel. The program might print sum before product, or print product before sum. |
||
=={{header|Ursa}}== |
|||
Ursa doesn't have arrays in the traditional sense. Its equivalent is the stream. All math operators take streams as arguments, so sums and products of streams can be found like this. |
|||
<syntaxhighlight lang="ursa">declare int<> stream |
|||
append 34 76 233 8 2 734 56 stream |
|||
# outputs 1143 |
|||
out (+ stream) endl console |
|||
# outputs 3.95961079808E11 |
|||
out (* stream) endl console</syntaxhighlight> |
|||
=={{header|Ursala}}== |
=={{header|Ursala}}== |
||
The reduction operator, :-, takes an associative binary function and a constant for the empty case. |
The reduction operator, :-, takes an associative binary function and a constant for the empty case. |
||
Natural numbers are unsigned and of unlimited size. |
Natural numbers are unsigned and of unlimited size. |
||
< |
<syntaxhighlight lang="ursala">#import nat |
||
#cast %nW |
#cast %nW |
||
sp = ^(sum:-0,product:-1) <62,43,46,40,29,55,51,82,59,92,48,73,93,35,42,25></ |
sp = ^(sum:-0,product:-1) <62,43,46,40,29,55,51,82,59,92,48,73,93,35,42,25></syntaxhighlight> |
||
output: |
|||
{{Out}} |
|||
<pre>(875,2126997171723931187788800000)</pre> |
<pre>(875,2126997171723931187788800000)</pre> |
||
=={{header|V}}== |
=={{header|V}}== |
||
< |
<syntaxhighlight lang="v">[sp dup 0 [+] fold 'product=' put puts 1 [*] fold 'sum=' put puts].</syntaxhighlight> |
||
Using it |
|||
{{Out|Using it}} |
|||
<lang v>[1 2 3 4 5] sp |
|||
<syntaxhighlight lang="v">[1 2 3 4 5] sp |
|||
= |
= |
||
product=15 |
product=15 |
||
sum=120</ |
sum=120</syntaxhighlight> |
||
=={{header|Vala}}== |
=={{header|Vala}}== |
||
<syntaxhighlight lang="vala">void main() { |
|||
<lang vala> |
|||
int sum = 0, prod = 1; |
|||
public static void main(){ |
|||
int[] data = { 1, 2, 3, 4 }; |
|||
foreach (int val in data) { |
|||
sum += val; |
|||
int[] array = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; |
|||
prod *= val; |
|||
} |
|||
foreach (int number in array){ |
|||
print(@"sum: $(sum)\nproduct: $(prod)"); |
|||
sum += number; |
|||
}</syntaxhighlight> |
|||
product *= number; |
|||
{{out}} |
|||
} |
|||
<pre>sum: 10 |
|||
product: 24</pre> |
|||
=={{header|VBA}}== |
|||
Assumes Excel is used. |
|||
<syntaxhighlight lang="vb">Sub Demo() |
|||
Dim arr |
|||
arr = Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) |
|||
Debug.Print "sum : " & Application.WorksheetFunction.Sum(arr) |
|||
Debug.Print "product : " & Application.WorksheetFunction.Product(arr) |
|||
End Sub</syntaxhighlight>{{Out}} |
|||
<pre>sum : 55 |
|||
product : 3628800</pre> |
|||
=={{header|VBScript}}== |
|||
<syntaxhighlight lang="vb">Function sum_and_product(arr) |
|||
sum = 0 |
|||
product = 1 |
|||
For i = 0 To UBound(arr) |
|||
sum = sum + arr(i) |
|||
product = product * arr(i) |
|||
Next |
|||
WScript.StdOut.Write "Sum: " & sum |
|||
WScript.StdOut.WriteLine |
|||
WScript.StdOut.Write "Product: " & product |
|||
WScript.StdOut.WriteLine |
|||
End Function |
|||
myarray = Array(1,2,3,4,5,6) |
|||
sum_and_product(myarray) |
|||
</syntaxhighlight> |
|||
{{Out}} |
|||
<pre> |
|||
Sum: 21 |
|||
Product: 720 |
|||
</pre> |
|||
=={{header|Visual Basic .NET}}== |
|||
{{trans|C#}} |
|||
<syntaxhighlight lang="vbnet">Module Program |
|||
Sub Main() |
|||
Dim arg As Integer() = {1, 2, 3, 4, 5} |
|||
Dim sum = arg.Sum() |
|||
Dim prod = arg.Aggregate(Function(runningProduct, nextFactor) runningProduct * nextFactor) |
|||
End Sub |
|||
End Module</syntaxhighlight> |
|||
=={{header|V (Vlang)}}== |
|||
<syntaxhighlight lang="v (vlang)"> |
|||
fn main() { |
|||
values := [1, 2, 3, 4, 5] |
|||
mut sum, mut prod := 0, 1 |
|||
for val in values { |
|||
sum += val |
|||
prod *= val |
|||
} |
|||
println("sum: $sum\nproduct: $prod") |
|||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
|||
<pre> |
|||
sum: 15 |
|||
product: 120 |
|||
</pre> |
|||
=={{header|Wart}}== |
=={{header|Wart}}== |
||
< |
<syntaxhighlight lang="wart">def (sum_prod nums) |
||
(list (+ @nums) (* @nums))</ |
(list (+ @nums) (* @nums))</syntaxhighlight> |
||
=={{header|WDTE}}== |
|||
<syntaxhighlight lang="wdte">let a => import 'arrays'; |
|||
let s => import 'stream'; |
|||
let sum array => a.stream array -> s.reduce 0 +; |
|||
let prod array => a.stream prod -> s.reduce 1 *;</syntaxhighlight> |
|||
=={{header|Wortel}}== |
|||
<syntaxhighlight lang="wortel">@sum [1 2 3 4] ; returns 10 |
|||
@prod [1 2 3 4] ; returns 24</syntaxhighlight> |
|||
=={{header|Wren}}== |
|||
{{libheader|Wren-math}} |
|||
<syntaxhighlight lang="wren">import "./math" for Nums |
|||
var a = [7, 10, 2, 4, 6, 1, 8, 3, 9, 5] |
|||
System.print("Array : %(a)") |
|||
System.print("Sum : %(Nums.sum(a))") |
|||
System.print("Product : %(Nums.prod(a))")</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
Array : [7, 10, 2, 4, 6, 1, 8, 3, 9, 5] |
|||
Sum : 55 |
|||
Product : 3628800 |
|||
</pre> |
|||
=={{header|XPL0}}== |
=={{header|XPL0}}== |
||
< |
<syntaxhighlight lang="xpl0">code CrLf=9, IntOut=11; |
||
func SumProd(A, L); |
func SumProd(A, L); |
||
Line 1,935: | Line 3,762: | ||
]; \SumSq |
]; \SumSq |
||
SumProd([1,2,3,4,5,6,7,8,9,10], 10)</ |
SumProd([1,2,3,4,5,6,7,8,9,10], 10)</syntaxhighlight> |
||
{{Out}} |
|||
Output: |
|||
<pre> |
<pre> |
||
55 |
55 |
||
3628800 |
3628800 |
||
</pre> |
</pre> |
||
=={{header|Wortel}}== |
|||
<lang wortel>@sum [1 2 3 4] ; returns 10 |
|||
@prod [1 2 3 4] ; returns 24</lang> |
|||
=={{header|XSLT}}== |
=={{header|XSLT}}== |
||
XSLT (or XPath rather) has a few built-in functions for reducing from a collection, but product is not among them. Because of referential transparency, one must resort to recursive solutions for general iterative operations upon collections. The following code represents the array by numeric values in <price> elements in the source document. |
XSLT (or XPath rather) has a few built-in functions for reducing from a collection, but product is not among them. Because of referential transparency, one must resort to recursive solutions for general iterative operations upon collections. The following code represents the array by numeric values in <price> elements in the source document. |
||
< |
<syntaxhighlight lang="xml"><xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> |
||
<xsl:output method="text" /> |
<xsl:output method="text" /> |
||
Line 1,985: | Line 3,808: | ||
</xsl:call-template> |
</xsl:call-template> |
||
</xsl:template> |
</xsl:template> |
||
</xsl:stylesheet></ |
</xsl:stylesheet></syntaxhighlight> |
||
=={{header|Yabasic}}== |
|||
{{trans|QBasic}} |
|||
<syntaxhighlight lang="yabasic">dim array(5) |
|||
data 1, 2, 3, 4, 5 |
|||
for index = 1 to arraysize(array(), 1) |
|||
read array(index) |
|||
next index |
|||
sum = 0 |
|||
prod = 1 |
|||
for index = 1 to arraysize(array(), 1) |
|||
sum = sum + array(index) |
|||
prod = prod * array(index) |
|||
next index |
|||
print "The sum is ", sum //15 |
|||
print "and the product is ", prod //120 |
|||
end</syntaxhighlight> |
|||
=={{header|Zig}}== |
|||
<syntaxhighlight lang="zig">const print = @import("std").debug.print; |
|||
pub fn main() void { |
|||
const numbers = [_]u8{ 1, 2, 3, 4, 5 }; |
|||
var sum: u8 = 0; |
|||
var product: u8 = 1; |
|||
for (numbers) |number| { |
|||
product *= number; |
|||
sum += number; |
|||
} |
|||
print("{} {}\n", .{ product, sum }); |
|||
}</syntaxhighlight> |
|||
=={{header|zkl}}== |
=={{header|zkl}}== |
||
{{trans|Clojure}} |
{{trans|Clojure}} |
||
< |
<syntaxhighlight lang="zkl">fcn sum(vals){vals.reduce('+,0)} |
||
fcn product(vals){vals.reduce('*,1)}</ |
fcn product(vals){vals.reduce('*,1)}</syntaxhighlight> |
||
<pre> |
<pre> |
||
sum(T(1,2,3,4)) //-->10 |
sum(T(1,2,3,4)) //-->10 |
||
product(T(1,2,3,4)) //-->24 |
product(T(1,2,3,4)) //-->24 |
||
</pre> |
</pre> |
||
=={{header|Zoea}}== |
|||
<syntaxhighlight lang="zoea"> |
|||
program: sum_and_product |
|||
case: 1 |
|||
input: [3,5] |
|||
output: [8,15] |
|||
case: 2 |
|||
input: [2,3,4] |
|||
output: [9,24] |
|||
</syntaxhighlight> |
|||
=={{header|Zoea Visual}}== |
|||
[http://zoea.co.uk/examples/zv-rc/Sum_and_product.png Sum and product of an array] |
Revision as of 14:25, 14 April 2024
You are encouraged to solve this task according to the task description, using any language you may know.
- Task
Compute the sum and product of an array of integers.
11l
V arr = [1, 2, 3, 4]
print(sum(arr))
print(product(arr))
- Output:
10 24
360 Assembly
* Sum and product of an array 20/04/2017
SUMPROD CSECT
USING SUMPROD,R15 base register
SR R3,R3 su=0
LA R5,1 pr=1
LA R6,1 i=1
DO WHILE=(CH,R6,LE,=AL2((PG-A)/4)) do i=1 to hbound(a)
LR R1,R6 i
SLA R1,2 *4
A R3,A-4(R1) su=su+a(i)
M R4,A-4(R1) pr=pr*a(i)
LA R6,1(R6) i++
ENDDO , enddo i
XDECO R3,PG su
XDECO R5,PG+12 pr
XPRNT PG,L'PG print
BR R14 exit
A DC F'1',F'2',F'3',F'4',F'5',F'6',F'7',F'8',F'9',F'10'
PG DS CL24 buffer
YREGS
END SUMPROD
- Output:
55 3628800
4D
ARRAY INTEGER($list;0)
For ($i;1;5)
APPEND TO ARRAY($list;$i)
End for
$sum:=0
$product:=1
For ($i;1;Size of array($list))
$sum:=$var+$list{$i}
$product:=$product*$list{$i}
End for
// since 4D v13
$sum:=sum($list)
AArch64 Assembly
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program sumandproduct64.s */
/************************************/
/* Constantes */
/************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
/*********************************/
/* Initialized data */
/*********************************/
.data
szMessSum: .asciz "Sum = "
szMessProd: .asciz "Product = "
szMessStart: .asciz "Program 64 bits start.\n"
szCarriageReturn: .asciz "\n"
szMessErreur: .asciz "Overflow ! \n"
tabArray: .quad 2, 11, 19, 90, 55,1000000
.equ TABARRAYSIZE, (. - tabArray) / 8
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
sZoneConv: .skip 24
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: // entry of program
ldr x0,qAdrszMessStart
bl affichageMess
ldr x2,qAdrtabArray
mov x1,#0 // indice
mov x0,#0 // sum init
1:
ldr x3,[x2,x1,lsl #3]
adds x0,x0,x3
bcs 99f
add x1,x1,#1
cmp x1,#TABARRAYSIZE
blt 1b
ldr x1,qAdrsZoneConv
bl conversion10 // decimal conversion
mov x0,#3 // number string to display
ldr x1,qAdrszMessSum
ldr x2,qAdrsZoneConv // insert conversion in message
ldr x3,qAdrszCarriageReturn
bl displayStrings // display message
ldr x2,qAdrtabArray
mov x1,#0 // indice
mov x0,#1 // product init
2:
ldr x3,[x2,x1,lsl #3]
mul x0,x3,x0
umulh x4,x3,x0
cmp x4,#0
bne 99f
add x1,x1,#1
cmp x1,#TABARRAYSIZE
blt 2b
ldr x1,qAdrsZoneConv
bl conversion10 // decimal conversion
mov x0,#3 // number string to display
ldr x1,qAdrszMessProd
ldr x2,qAdrsZoneConv // insert conversion in message
ldr x3,qAdrszCarriageReturn
bl displayStrings // display message
b 100f
99:
ldr x0,qAdrszMessErreur
bl affichageMess
100: // standard end of the program
mov x0, #0 // return code
mov x8,EXIT
svc #0 // perform the system call
qAdrszCarriageReturn: .quad szCarriageReturn
qAdrsZoneConv: .quad sZoneConv
qAdrszMessSum: .quad szMessSum
qAdrszMessProd: .quad szMessProd
qAdrszMessErreur: .quad szMessErreur
qAdrszMessStart: .quad szMessStart
qAdrtabArray: .quad tabArray
/***************************************************/
/* display multi strings */
/* new version 24/05/2023 */
/***************************************************/
/* x0 contains number strings address */
/* x1 address string1 */
/* x2 address string2 */
/* x3 address string3 */
/* x4 address string4 */
/* x5 address string5 */
/* x6 address string5 */
displayStrings: // INFO: displayStrings
stp x7,lr,[sp,-16]! // save registers
stp x2,fp,[sp,-16]! // save registers
add fp,sp,#32 // save paraméters address (4 registers saved * 8 bytes)
mov x7,x0 // save strings number
cmp x7,#0 // 0 string -> end
ble 100f
mov x0,x1 // string 1
bl affichageMess
cmp x7,#1 // number > 1
ble 100f
mov x0,x2
bl affichageMess
cmp x7,#2
ble 100f
mov x0,x3
bl affichageMess
cmp x7,#3
ble 100f
mov x0,x4
bl affichageMess
cmp x7,#4
ble 100f
mov x0,x5
bl affichageMess
cmp x7,#5
ble 100f
mov x0,x6
bl affichageMess
100:
ldp x2,fp,[sp],16 // restaur registers
ldp x7,lr,[sp],16 // restaur registers
ret
/***************************************************/
/* ROUTINES INCLUDE */
/***************************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeARM64.inc"
- Output:
Program 64 bits start. Sum = 1000177 Product = 2069100000000
ACL2
(defun sum (xs)
(if (endp xs)
0
(+ (first xs)
(sum (rest xs)))))
(defun prod (xs)
(if (endp xs)
1
(* (first xs)
(prod (rest xs)))))
Action!
DEFINE LAST="6"
PROC Main()
INT ARRAY data=[1 2 3 4 5 6 7]
BYTE i
INT a,res
res=0
FOR i=0 TO LAST
DO
a=data(i)
PrintI(a)
IF i=LAST THEN
Put('=)
ELSE
Put('+)
FI
res==+a
OD
PrintIE(res)
res=1
FOR i=0 TO LAST
DO
a=data(i)
PrintI(a)
IF i=LAST THEN
Put('=)
ELSE
Put('*)
FI
res=res*a
OD
PrintIE(res)
RETURN
- Output:
Screenshot from Atari 8-bit computer
1+2+3+4+5+6+7=28 1*2*3*4*5*6*7=5040
ActionScript
package {
import flash.display.Sprite;
public class SumAndProduct extends Sprite
{
public function SumAndProduct()
{
var arr:Array = [1, 2, 3, 4, 5];
var sum:int = 0;
var prod:int = 1;
for (var i:int = 0; i < arr.length; i++)
{
sum += arr[i];
prod *= arr[i];
}
trace("Sum: " + sum); // 15
trace("Product: " + prod); // 120
}
}
}
Ada
type Int_Array is array(Integer range <>) of Integer;
array : Int_Array := (1,2,3,4,5,6,7,8,9,10);
Sum : Integer := 0;
for I in array'range loop
Sum := Sum + array(I);
end loop;
Define the product function
function Product(Item : Int_Array) return Integer is
Prod : Integer := 1;
begin
for I in Item'range loop
Prod := Prod * Item(I);
end loop;
return Prod;
end Product;
This function will raise the predefined exception Constraint_Error if the product overflows the values represented by type Integer
Aime
void
compute(integer &s, integer &p, list l)
{
integer v;
s = 0;
p = 1;
for (, v in l) {
s += v;
p *= v;
}
}
integer
main(void)
{
integer sum, product;
compute(sum, product, list(2, 3, 5, 7, 11, 13, 17, 19));
o_form("~\n~\n", sum, product);
return 0;
}
- Output:
77 9699690
ALGOL 68
main:(
INT default upb := 3;
MODE INTARRAY = [default upb]INT;
INTARRAY array = (1,2,3,4,5,6,7,8,9,10);
INT sum := 0;
FOR i FROM LWB array TO UPB array DO
sum +:= array[i]
OD;
# Define the product function #
PROC int product = (INTARRAY item)INT:
(
INT prod :=1;
FOR i FROM LWB item TO UPB item DO
prod *:= item[i]
OD;
prod
) # int product # ;
printf(($" Sum: "g(0)$,sum,$", Product:"g(0)";"l$,int product(array)))
)
- Output:
Sum: 55, Product:3628800;
ALGOL W
begin
% computes the sum and product of intArray %
% the results are returned in sum and product %
% the bounds of the array must be specified in lb and ub %
procedure sumAndProduct( integer array intArray ( * )
; integer value lb, ub
; integer result sum, product
) ;
begin
sum := 0;
product := 1;
for i := lb until ub
do begin
sum := sum + intArray( i );
product := product * intArray( i );
end for_i ;
end sumAndProduct ;
% test the sumAndProduct procedure %
begin
integer array v ( 1 :: 10 );
integer sum, product;
for i := 1 until 10 do v( i ) := i;
sumAndProduct( v, 1, 10, sum, product );
write( sum, product );
end
end.
- Output:
55 3628800
APL
sum ← +/ ⍝ sum (+) over (/) an array
prod ← ×/ ⍝ product (×) over (/) an array
a ← 1 2 3 4 5 ⍝ assign a literal array to variable 'a'
sum a ⍝ or simply: +/a
15
prod a ⍝ or simply: ×/a
120
What follows ⍝ is a comment and / is usually known as reduce in APL. The use of the sum and prod functions is not necessary and was added only to please people baffled by the extreme conciseness of using APL symbols.
using the pair (⍮) primitive function
⎕ ← (+/ ⍮ ×/) 1 2 3 4 5
15 120
Spaces are optional except as separators between array elements.
AppleScript
set array to {1, 2, 3, 4, 5}
set sum to 0
set product to 1
repeat with i in array
set sum to sum + i
set product to product * i
end repeat
Condensed version of above, which also prints the results :
set {array, sum, product} to {{1, 2, 3, 4, 5}, 0, 1}
repeat with i in array
set {sum, product} to {sum + i, product * i}
end repeat
return sum & " , " & product as string
- Output:
"15 , 120"
Or, using an AppleScript implementation of fold/reduce:
on summed(a, b)
a + b
end summed
on product(a, b)
a * b
end product
-- TEST -----------------------------------------------------------------------
on run
set xs to enumFromTo(1, 10)
{xs, ¬
{sum:foldl(summed, 0, xs)}, ¬
{product:foldl(product, 1, xs)}}
--> {{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, {sum:55}, {product:3628800}}
end run
-- GENERIC FUNCTIONS ----------------------------------------------------------
-- enumFromTo :: Int -> Int -> [Int]
on enumFromTo(m, n)
if n < m then
set d to -1
else
set d to 1
end if
set lst to {}
repeat with i from m to n by d
set end of lst to i
end repeat
return lst
end enumFromTo
-- foldl :: (a -> b -> a) -> a -> [b] -> a
on foldl(f, startValue, xs)
tell mReturn(f)
set v to startValue
set lng to length of xs
repeat with i from 1 to lng
set v to |λ|(v, item i of xs, i, xs)
end repeat
return v
end tell
end foldl
-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: Handler -> Script
on mReturn(f)
if class of f is script then
f
else
script
property |λ| : f
end script
end if
end mReturn
- Output:
{{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, {sum:55}, {product:3628800}}
ARM Assembly
/* ARM assembly Raspberry PI */
/* program sumandproduct.s */
/* REMARK 1 : this program use routines in a include file
see task Include a file language arm assembly
for the routine affichageMess conversion10
see at end of this program the instruction include */
/* for constantes see task include a file in arm assembly */
/************************************/
/* Constantes */
/************************************/
.include "../constantes.inc"
/*********************************/
/* Initialized data */
/*********************************/
.data
szMessSum: .asciz "Sum = "
szMessProd: .asciz "Product = "
szMessStart: .asciz "Program 32 bits start.\n"
szCarriageReturn: .asciz "\n"
szMessErreur: .asciz "Overflow ! \n"
tabArray: .int 2, 11, 19, 90, 55,1000
.equ TABARRAYSIZE, (. - tabArray) / 4
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
sZoneConv: .skip 24
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: @ entry of program
ldr r0,iAdrszMessStart
bl affichageMess
ldr r2,iAdrtabArray
mov r1,#0 @ indice
mov r0,#0 @ sum init
1:
ldr r3,[r2,r1,lsl #2]
adds r0,r0,r3
bcs 99f
add r1,r1,#1
cmp r1,#TABARRAYSIZE
blt 1b
ldr r1,iAdrsZoneConv
bl conversion10 @ decimal conversion
mov r3,#0
strb r3,[r1,r0]
mov r0,#3 @ number string to display
ldr r1,iAdrszMessSum
ldr r2,iAdrsZoneConv @ insert conversion in message
ldr r3,iAdrszCarriageReturn
bl displayStrings @ display message
ldr r2,iAdrtabArray
mov r1,#0 @ indice
mov r0,#1 @ product init
2:
ldr r3,[r2,r1,lsl #2]
umull r0,r4,r3,r0
cmp r4,#0
bne 99f
add r1,r1,#1
cmp r1,#TABARRAYSIZE
blt 2b
ldr r1,iAdrsZoneConv
bl conversion10 @ decimal conversion
mov r3,#0
strb r3,[r1,r0]
mov r0,#3 @ number string to display
ldr r1,iAdrszMessProd
ldr r2,iAdrsZoneConv @ insert conversion in message
ldr r3,iAdrszCarriageReturn
bl displayStrings @ display message
b 100f
99:
ldr r0,iAdrszMessErreur
bl affichageMess
100: @ standard end of the program
mov r0, #0 @ return code
mov r7, #EXIT @ request to exit program
svc #0 @ perform the system call
iAdrszCarriageReturn: .int szCarriageReturn
iAdrsZoneConv: .int sZoneConv
iAdrszMessSum: .int szMessSum
iAdrszMessProd: .int szMessProd
iAdrszMessErreur: .int szMessErreur
iAdrszMessStart: .int szMessStart
iAdrtabArray: .int tabArray
/***************************************************/
/* display multi strings */
/***************************************************/
/* r0 contains number strings address */
/* r1 address string1 */
/* r2 address string2 */
/* r3 address string3 */
/* other address on the stack */
/* thinck to add number other address * 4 to add to the stack */
displayStrings: @ INFO: displayStrings
push {r1-r4,fp,lr} @ save des registres
add fp,sp,#24 @ save paraméters address (6 registers saved * 4 bytes)
mov r4,r0 @ save strings number
cmp r4,#0 @ 0 string -> end
ble 100f
mov r0,r1 @ string 1
bl affichageMess
cmp r4,#1 @ number > 1
ble 100f
mov r0,r2
bl affichageMess
cmp r4,#2
ble 100f
mov r0,r3
bl affichageMess
cmp r4,#3
ble 100f
mov r3,#3
sub r2,r4,#4
1: @ loop extract address string on stack
ldr r0,[fp,r2,lsl #2]
bl affichageMess
subs r2,#1
bge 1b
100:
pop {r1-r4,fp,pc}
/***************************************************/
/* ROUTINES INCLUDE */
/***************************************************/
.include "../affichage.inc"
- Output:
Program 32 bits start. Sum = 1177 Product = 2069100000
Arturo
arr: 1..10
print ["Sum =" sum arr]
print ["Product =" product arr]
- Output:
Sum = 55 Product = 3628800
Asymptote
int[] matriz = {1,2,3,4,5};
int suma = 0, prod = 1;
for (int p : matriz) {
suma += p;
prod *= p;
}
write("Sum = ", suma);
write("Product = ", prod);
- Output:
Sum = 15 Product = 120
AutoHotkey
numbers = 1,2,3,4,5
product := 1
loop, parse, numbers, `,
{
sum += A_LoopField
product *= A_LoopField
}
msgbox, sum = %sum%`nproduct = %product%
AWK
For array input, it is easiest to "deserialize" it from a string with the split() function.
$ awk 'func sum(s){split(s,a);r=0;for(i in a)r+=a[i];return r}{print sum($0)}'
1 2 3 4 5 6 7 8 9 10
55
$ awk 'func prod(s){split(s,a);r=1;for(i in a)r*=a[i];return r}{print prod($0)}'
1 2 3 4 5 6 7 8 9 10
3628800
Babel
main: { [2 3 5 7 11 13] sp }
sum! : { <- 0 -> { + } eachar }
product!: { <- 1 -> { * } eachar }
sp!:
{ dup
sum %d cr <<
product %d cr << }
Result:
41
30030
Perhaps better Babel:
main:
{ [2 3 5 7 11 13]
ar2ls dup cp
<- sum_stack ->
prod_stack
%d cr <<
%d cr << }
sum_stack:
{ { give
{ + }
{ depth 1 > }
do_while } nest }
prod_stack:
{ { give
{ * }
{ depth 1 > }
do_while } nest }
The nest operator creates a kind of argument-passing context - it saves whatever is on Top-of-Stack (TOS), saves the old stack, clears the stack and places the saved TOS on the new, cleared stack. This permits a section to monopolize the stack. At the end of the nest context, whatever is on TOS will be "passed back" to the original stack which will be restored.
The depth operator returns the current depth of the stack.
BASIC
dim array(5) as integer = { 1, 2, 3, 4, 5 }
dim sum as integer = 0
dim prod as integer = 1
for index as integer = lbound(array) to ubound(array)
sum += array(index)
prod *= array(index)
next
Applesoft BASIC
10 N = 5
20 S = 0:P = 1: DATA 1,2,3,4,5
30 N = N - 1: DIM A(N)
40 FOR I = 0 TO N
50 READ A(I): NEXT
60 FOR I = 0 TO N
70 S = S + A(I):P = P * A(I)
80 NEXT
90 PRINT "SUM="S,"PRODUCT="P
Atari BASIC
Almost the same code works in Atari BASIC, but you can't READ directly into arrays, leave the variable off a NEXT, or concatenate values in PRINT without semicolons between them:
10 N = 5
20 S = 0:P = 1: DATA 1,2,3,4,5
30 N = N - 1: DIM A(N)
40 FOR I = 0 TO N
50 READ X:A(I) = X: NEXT I
60 FOR I = 0 TO N
70 S = S + A(I):P = P * A(I)
80 NEXT I
90 PRINT "SUM=";S,"PRODUCT=";P
BaCon
'--- set some values into the array
DECLARE a[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10 } TYPE int
sum = 0
product = 1
i = 1
WHILE a[i] <= 10
sum = sum + a[i]
product = product * a[i]
INCR i
WEND
PRINT "The sum is ",sum
PRINT "The product is ",product
Chipmunk Basic
10 rem Sum and product of an array
20 dim array(4)' array de 5 eltos.
30 data 1,2,3,4,5
40 for index = 0 to ubound(array)
50 read array(index)
60 next index
70 sum = 0
80 prod = 1
90 for index = 0 to 4 ubound(array)
100 sum = sum+array(index)
110 prod = prod*array(index)
120 next index
130 print "The sum is ";sum
140 print "and the product is ";prod
150 end
BBC BASIC
DIM array%(5)
array%() = 1, 2, 3, 4, 5, 6
PRINT "Sum of array elements = " ; SUM(array%())
product% = 1
FOR I% = 0 TO DIM(array%(),1)
product% *= array%(I%)
NEXT
PRINT "Product of array elements = " ; product%
IS-BASIC
100 RANDOMIZE
110 LET N=5
120 NUMERIC A(1 TO N)
130 LET SUM=0:LET PROD=1
140 FOR I=1 TO N
150 LET A(I)=RND(9)+1
160 PRINT A(I);
170 NEXT
180 PRINT
190 FOR I=1 TO N
200 LET SUM=SUM+A(I):LET PROD=PROD*A(I)
210 NEXT
220 PRINT "Sum =";SUM,"Product =";PROD
BASIC256
arraybase 1
dim array(5)
array[1] = 1
array[2] = 2
array[3] = 3
array[4] = 4
array[5] = 5
sum = 0
prod = 1
for index = 1 to array[?]
sum += array[index]
prod *= array[index]
next index
print "The sum is "; sum #15
print "and the product is "; prod #120
end
bc
a[0] = 3.0
a[1] = 1
a[2] = 4.0
a[3] = 1.0
a[4] = 5
a[5] = 9.00
n = 6
p = 1
for (i = 0; i < n; i++) {
s += a[i]
p *= a[i]
}
"Sum: "; s
"Product: "; p
Befunge
The program first reads the number of elements in the array, then the elements themselves (each number on a separate line) and calculates their sum.
0 &>: #v_ $. @
>1- \ & + \v
^ <
BQN
Getting the sum and product as a two element array fits nicely within a tacit fork pattern.
- Sum
+´
- Paired with
⋈
- Product
×´
SumProd ← +´⋈×´
+´⋈×´
SumProd 1‿2‿3‿4‿5
⟨ 15 120 ⟩
Bracmat
( ( sumprod
= sum prod num
. 0:?sum
& 1:?prod
& ( !arg
: ?
( #%?num ?
& !num+!sum:?sum
& !num*!prod:?prod
& ~
)
| (!sum.!prod)
)
)
& out$sumprod$(2 3 5 7 11 13 17 19)
);
- Output:
77.9699690
Bruijn
:import std/List .
:import std/Math .
arr (+1) : ((+2) : ((+3) : {}(+4)))
main [∑arr : ∏arr]
C
/* using pointer arithmetic (because we can, I guess) */
int arg[] = { 1,2,3,4,5 };
int arg_length = sizeof(arg)/sizeof(arg[0]);
int *end = arg+arg_length;
int sum = 0, prod = 1;
int *p;
for (p = arg; p!=end; ++p) {
sum += *p;
prod *= *p;
}
C#
int sum = 0, prod = 1;
int[] arg = { 1, 2, 3, 4, 5 };
foreach (int value in arg) {
sum += value;
prod *= value;
}
Alternative using Linq (C# 3)
int[] arg = { 1, 2, 3, 4, 5 };
int sum = arg.Sum();
int prod = arg.Aggregate((runningProduct, nextFactor) => runningProduct * nextFactor);
C++
#include <numeric>
#include <functional>
int arg[] = { 1, 2, 3, 4, 5 };
int sum = std::accumulate(arg, arg+5, 0, std::plus<int>());
// or just
// std::accumulate(arg, arg + 5, 0);
// since plus() is the default functor for accumulate
int prod = std::accumulate(arg, arg+5, 1, std::multiplies<int>());
Template alternative:
// this would be more elegant using STL collections
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;
}
template <typename T> T prod (const T *array, const unsigned n)
{
T accum = 1;
for (unsigned i=0; i<n; i++)
accum *= array[i];
return accum;
}
#include <iostream>
using std::cout;
using std::endl;
int main ()
{
int aint[] = {1, 2, 3};
cout << sum(aint,3) << " " << prod(aint, 3) << endl;
float aflo[] = {1.1, 2.02, 3.003, 4.0004};
cout << sum(aflo,4) << " " << prod(aflo,4) << endl;
return 0;
}
Chef
Sum and Product of Numbers as a Piece of Cake.
This recipe sums N given numbers.
Ingredients.
1 N
0 sum
1 product
1 number
Method.
Put sum into 1st mixing bowl.
Put product into 2nd mixing bowl.
Take N from refrigerator.
Chop N.
Take number from refrigerator.
Add number into 1st mixing bowl.
Combine number into 2nd mixing bowl.
Chop N until choped.
Pour contents of 2nd mixing bowl into the baking dish.
Pour contents of 1st mixing bowl into the baking dish.
Serves 1.
Clean
array = {1, 2, 3, 4, 5}
Sum = sum [x \\ x <-: array]
Prod = foldl (*) 1 [x \\ x <-: array]
Clojure
(defn sum [vals] (reduce + vals))
(defn product [vals] (reduce * vals))
CLU
sum_and_product = proc (a: array[int]) returns (int,int) signals (overflow)
sum: int := 0
prod: int := 1
for i: int in array[int]$elements(a) do
sum := sum + i
prod := prod * i
end resignal overflow
return(sum, prod)
end sum_and_product
start_up = proc ()
arr: array[int] := array[int]$[1,2,3,4,5,6,7,8,9,10]
sum, prod: int := sum_and_product(arr)
po: stream := stream$primary_output()
stream$putl(po, "Sum = " || int$unparse(sum))
stream$putl(po, "Product = " || int$unparse(prod))
end start_up
- Output:
Sum = 55 Product = 3628800
COBOL
IDENTIFICATION DIVISION.
PROGRAM-ID. array-sum-and-product.
DATA DIVISION.
WORKING-STORAGE SECTION.
78 Array-Size VALUE 10.
01 array-area VALUE "01020304050607080910".
03 array PIC 99 OCCURS Array-Size TIMES.
01 array-sum PIC 9(8).
01 array-product PIC 9(10) VALUE 1.
01 i PIC 99.
PROCEDURE DIVISION.
PERFORM VARYING i FROM 1 BY 1 UNTIL Array-Size < i
ADD array (i) TO array-sum
MULTIPLY array (i) BY array-product
END-PERFORM
DISPLAY "Sum: " array-sum
DISPLAY "Product: " array-product
GOBACK
.
CoffeeScript
sum = (array) ->
array.reduce (x, y) -> x + y
product = (array) ->
array.reduce (x, y) -> x * y
ColdFusion
Sum of an Array,
<cfset Variables.myArray = [1,2,3,4,5,6,7,8,9,10]>
<cfoutput>#ArraySum(Variables.myArray)#</cfoutput>
Product of an Array,
<cfset Variables.myArray = [1,2,3,4,5,6,7,8,9,10]>
<cfset Variables.Product = 1>
<cfloop array="#Variables.myArray#" index="i">
<cfset Variables.Product *= i>
</cfloop>
<cfoutput>#Variables.Product#</cfoutput>
Common Lisp
(let ((data #(1 2 3 4 5))) ; the array
(values (reduce #'+ data) ; sum
(reduce #'* data))) ; product
The loop macro also has support for sums.
(loop for i in '(1 2 3 4 5) sum i)
Crystal
Declarative
def sum_product(a)
{ a.sum(), a.product() }
end
Imperative
def sum_product_imperative(a)
sum, product = 0, 1
a.each do |e|
sum += e
product *= e
end
{sum, product}
end
require "benchmark"
Benchmark.ips do |x|
x.report("declarative") { sum_product [1, 2, 3, 4, 5] }
x.report("imperative") { sum_product_imperative [1, 2, 3, 4, 5] }
end
declarative 8.1M (123.45ns) (± 2.99%) 65 B/op 1.30× slower imperative 10.57M ( 94.61ns) (± 2.96%) 65 B/op fastest
D
import std.stdio;
void main() {
immutable array = [1, 2, 3, 4, 5];
int sum = 0;
int prod = 1;
foreach (x; array) {
sum += x;
prod *= x;
}
writeln("Sum: ", sum);
writeln("Product: ", prod);
}
- Output:
Sum: 15 Product: 120
Compute sum and product of array in one pass (same output):
import std.stdio, std.algorithm, std.typecons;
void main() {
immutable array = [1, 2, 3, 4, 5];
// Results are stored in a 2-tuple
immutable r = reduce!(q{a + b}, q{a * b})(tuple(0, 1), array);
writeln("Sum: ", r[0]);
writeln("Product: ", r[1]);
}
dc
1 3 5 7 9 11 13 0ss1sp[dls+sslp*spz0!=a]dsax[Sum: ]Plsp[Product: ]Plpp
Sum: 49
Product: 135135
Delphi
program SumAndProductOfArray;
{$APPTYPE CONSOLE}
var
i: integer;
lIntArray: array [1 .. 5] of integer = (1, 2, 3, 4, 5);
lSum: integer = 0;
lProduct: integer = 1;
begin
for i := 1 to length(lIntArray) do
begin
Inc(lSum, lIntArray[i]);
lProduct := lProduct * lIntArray[i]
end;
Write('Sum: ');
Writeln(lSum);
Write('Product: ');
Writeln(lProduct);
end.
E
pragma.enable("accumulator")
accum 0 for x in [1,2,3,4,5] { _ + x }
accum 1 for x in [1,2,3,4,5] { _ * x }
EasyLang
array[] = [ 5 1 19 25 12 1 14 7 ]
product = 1
for item in array[]
sum += item
product *= item
.
print "Sum: " & sum
print "Product: " & product
- Output:
Sum: 84 Product: 2793000
Eiffel
class
APPLICATION
create
make
feature {NONE}
make
local
test: ARRAY [INTEGER]
do
create test.make_empty
test := <<5, 1, 9, 7>>
io.put_string ("Sum: " + sum (test).out)
io.new_line
io.put_string ("Product: " + product (test).out)
end
sum (ar: ARRAY [INTEGER]): INTEGER
-- Sum of the items of the array 'ar'.
do
across
ar.lower |..| ar.upper as c
loop
Result := Result + ar [c.item]
end
end
product (ar: ARRAY [INTEGER]): INTEGER
-- Product of the items of the array 'ar'.
do
Result := 1
across
ar.lower |..| ar.upper as c
loop
Result := Result * ar [c.item]
end
end
end
- Output:
Sum of the elements of the array: 30 Product of the elements of the array: 3840
Elena
ELENA 5.0:
import system'routines;
import extensions;
public program()
{
var list := new int[]{1, 2, 3, 4, 5 };
var sum := list.summarize(new Integer());
var product := list.accumulate(new Integer(1), (var,val => var * val));
}
Elixir
When an accumulator is omitted, the first element of the collection is used as the initial value of acc.
iex(26)> Enum.reduce([1,2,3,4,5], 0, fn x,acc -> x+acc end)
15
iex(27)> Enum.reduce([1,2,3,4,5], 1, fn x,acc -> x*acc end)
120
iex(28)> Enum.reduce([1,2,3,4,5], fn x,acc -> x+acc end)
15
iex(29)> Enum.reduce([1,2,3,4,5], fn x,acc -> x*acc end)
120
iex(30)> Enum.reduce([], 0, fn x,acc -> x+acc end)
0
iex(31)> Enum.reduce([], 1, fn x,acc -> x*acc end)
1
iex(32)> Enum.reduce([], fn x,acc -> x+acc end)
** (Enum.EmptyError) empty error
(elixir) lib/enum.ex:1287: Enum.reduce/2
iex(32)> Enum.reduce([], fn x,acc -> x*acc end)
** (Enum.EmptyError) empty error
(elixir) lib/enum.ex:1287: Enum.reduce/2
The function with sum
Enum.sum([1,2,3,4,5]) #=> 15
Emacs Lisp
(let ((array [1 2 3 4 5]))
(apply #'+ (append array nil))
(apply #'* (append array nil)))
(require 'cl-lib)
(let ((array [1 2 3 4 5]))
(cl-reduce #'+ array)
(cl-reduce #'* array))
(require 'seq)
(let ((array [1 2 3 4 5]))
(seq-reduce #'+ array 0)
(seq-reduce #'* array 1))
Erlang
Using the standard libraries:
% create the list:
L = lists:seq(1, 10).
% and compute its sum:
S = lists:sum(L).
P = lists:foldl(fun (X, P) -> X * P end, 1, L).
To compute sum and products in one pass:
{Prod,Sum} = lists:foldl(fun (X, {P,S}) -> {P*X,S+X} end, {1,0}, lists:seq(1,10)).
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).
Euler
In Euler, a list must be assigned to a variable in order for it to be subscripted.
begin new sumAndProduct; new sumField; new productField; sumAndProduct <- ` formal array; begin new sum; new product; new i; new v; label arrayLoop; v <- array; sum <- 0; product <- 1; i <- 0; arrayLoop: if [ i <- i + 1 ] <= length array then begin sum <- sum + v[ i ]; product <- product * v[ i ]; goto arrayLoop end else 0; sumField <- 1; productField <- 2; ( sum, product ) end '; begin new sp; sp <- sumAndProduct( ( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ) ); out sp[ sumField ]; out sp[ productField ] end end $
Euphoria
sequence array
integer sum,prod
array = { 1, 2, 3, 4, 5 }
sum = 0
prod = 1
for i = 1 to length(array) do
sum += array[i]
prod *= array[i]
end for
printf(1,"sum is %d\n",sum)
printf(1,"prod is %d\n",prod)
- Output:
sum is 15 prod is 120
F#
let numbers = [| 1..10 |]
let sum = numbers |> Array.sum
let product = numbers |> Array.reduce (*)
Factor
1 5 1 <range> [ sum . ] [ product . ] bi
15 120
{ 1 2 3 4 } [ sum ] [ product ] bi
10 24
sum and product are defined in the sequences vocabulary:
: sum ( seq -- n ) 0 [ + ] reduce ;
: product ( seq -- n ) 1 [ * ] reduce ;
FALSE
Strictly speaking, there are no arrays in FALSE. However, a number of elements on the stack could be considered an array. The implementation below assumes the length of the array on top of the stack, and the actual items below it. Note that this implementation does remove the "array" from the stack, so in case the original values need to be retained, a copy should be provided before executing this logic.
1 2 3 4 5 {input "array"}
5 {length of input}
0s: {sum}
1p: {product}
[$0=~][1-\$s;+s:p;*p:]#%
"Sum: "s;."
Product: "p;.
- Output:
Sum: 15 Product: 120
Fantom
class Main
{
public static Void main ()
{
Int[] array := (1..20).toList
// you can use a loop
Int sum := 0
array.each |Int n| { sum += n }
echo ("Sum of array is : $sum")
Int product := 1
array.each |Int n| { product *= n }
echo ("Product of array is : $product")
// or use 'reduce'
// 'reduce' takes a function,
// the first argument is the accumulated value
// and the second is the next item in the list
sum = array.reduce(0) |Obj r, Int v -> Obj|
{
return (Int)r + v
}
echo ("Sum of array : $sum")
product = array.reduce(1) |Obj r, Int v -> Obj|
{
return (Int)r * v
}
echo ("Product of array : $product")
}
}
Fermat
[a]:=[(1,1,2,3,5,8,13)];
!!Sigma<i=1,7>[a[i]];
!!Prod<i=1,7>[a[i]];
- Output:
33 3120
Forth
: third ( a b c -- a b c a ) 2 pick ;
: reduce ( xt n addr cnt -- n' ) \ where xt ( a b -- n )
cells bounds do i @ third execute cell +loop nip ;
create a 1 , 2 , 3 , 4 , 5 ,
' + 0 a 5 reduce . \ 15
' * 1 a 5 reduce . \ 120
Fortran
In ISO Fortran 90 and later, use SUM and PRODUCT intrinsics:
integer, dimension(10) :: a = (/ (i, i=1, 10) /)
integer :: sresult, presult
sresult = sum(a)
presult = product(a)
FreeBASIC
' FB 1.05.0 Win64
Dim a(1 To 4) As Integer = {1, 4, 6, 3}
Dim As Integer i, sum = 0, prod = 1
For i = 1 To 4
sum += a(i)
prod *= a(i)
Next
Print "Sum ="; sum
Print "Product ="; prod
Print
Print "Press any key to quit"
Sleep
- Output:
Sum = 14 Product = 72
FreePascal
program sumproduct;
var
a:array[0..4] of integer =(1,2,3,4,5);
i:integer;
sum :Cardinal = 0;
prod:Cardinal = 1;
begin
for i in a do
sum :=sum+i;
for i in a do
prod:=prod * i;
writeln('sum: ',sum);
writeln('prod:',prod);
end.
- Output:
15 120
Frink
a = [1,2,3,5,7]
sum[a]
product[a]
FutureBasic
Traditional
local fn Sum( mutArr as CFMutableArrayRef ) as float
NSInteger i, count, value = 0
float sum = 0
count = fn ArrayCount( mutArr )
for i = 0 to count -1
value = fn NumberIntegerValue( fn ArrayObjectAtIndex( mutArr, i ) )
sum += value
next
end fn = sum
local fn Product( mutArr as CFMutableArrayRef ) as float
NSInteger i, count, value = 0
float prod = 0
count = fn ArrayCount( mutArr )
for i = 0 to count -1
value = fn NumberIntegerValue( fn ArrayObjectAtIndex( mutArr, i ) )
prod *= value
next
end fn = prod
Sum of array elements with key-value coding
local fn NumericalArraySum( array as CFArrayRef ) as CFNumberRef
end fn = fn ObjectValueForKeyPath( array, @"@sum.self" )
printf @"%@", fn NumericalArraySum( @[@0.0454, @-1.3534, @0.345, @65, @-0.345, @1.35] )
HandleEvents
- Output:
65.042
Fōrmulæ
Fōrmulæ programs are not textual, visualization/edition of programs is done showing/manipulating structures but not text. Moreover, there can be multiple visual representations of the same program. Even though it is possible to have textual representation —i.e. XML, JSON— they are intended for storage and transfer purposes more than visualization and edition.
Programs in Fōrmulæ are created/edited online in its website.
In this page you can see and run the program(s) related to this task and their results. You can also change either the programs or the parameters they are called with, for experimentation, but remember that these programs were created with the main purpose of showing a clear solution of the task, and they generally lack any kind of validation.
Solution
Test cases
Empty sum and empty product:
Gambas
Click this link to run this code
Public Sub Main()
Dim iList As Integer[] = [1, 2, 3, 4, 5]
Dim iSum, iCount As Integer
Dim iPrd As Integer = 1
For iCount = 0 To iList.Max
iSum += iList[iCount]
iPrd *= iList[iCount]
Next
Print "The Sum =\t" & iSum
Print "The Product =\t" & iPrd
End
Output:
The Sum = 15 The Product = 120
GAP
v := [1 .. 8];
Sum(v);
# 36
Product(v);
# 40320
# You can sum or multiply the result of a function
Sum(v, n -> n^2);
# 204
Product(v, n -> 1/n);
# 1/40320
GFA Basic
DIM a%(10)
' put some values into the array
FOR i%=1 TO 10
a%(i%)=i%
NEXT i%
'
sum%=0
product%=1
FOR i%=1 TO 10
sum%=sum%+a%(i%)
product%=product%*a%(i%)
NEXT i%
'
PRINT "Sum is ";sum%
PRINT "Product is ";product%
Go
- Implementation
package main
import "fmt"
func main() {
sum, prod := 0, 1
for _, x := range []int{1,2,5} {
sum += x
prod *= x
}
fmt.Println(sum, prod)
}
- Output:
8 10
- Library
package main
import (
"fmt"
"github.com/gonum/floats"
)
var a = []float64{1, 2, 5}
func main() {
fmt.Println("Sum: ", floats.Sum(a))
fmt.Println("Product:", floats.Prod(a))
}
- Output:
Sum: 8 Product: 10
Groovy
Groovy adds a "sum()" method for collections, but not a "product()" method:
[1,2,3,4,5].sum()
However, for general purpose "reduction" or "folding" operations, Groovy does provide an "inject()" method for collections similar to "inject" in Ruby.
[1,2,3,4,5].inject(0) { sum, val -> sum + val }
[1,2,3,4,5].inject(1) { prod, val -> prod * val }
You can also combine these operations:
println ([1,2,3,4,5].inject([sum: 0, product: 1]) { result, value ->
[sum: result.sum + value, product: result.product * value]})
GW-BASIC
10 REM Create an array with some test data in it
20 DIM A(5)
30 FOR I = 1 TO 5: READ A(I): NEXT I
40 DATA 1, 2, 3, 4, 5
50 REM Find the sum of elements in the array
60 S = 0
65 P = 1
70 FOR I = 1 TO 5
72 S = SUM + A(I)
75 P = P * A(I)
77 NEXT I
80 PRINT "The sum is "; S;
90 PRINT " and the product is "; P
Haskell
For lists, sum and product are already defined in the Prelude:
values = [1..10]
s = sum values -- the easy way
p = product values
s1 = foldl (+) 0 values -- the hard way
p1 = foldl (*) 1 values
To do the same for an array, just convert it lazily to a list:
import Data.Array
values = listArray (1,10) [1..10]
s = sum . elems $ values
p = product . elems $ values
Or perhaps:
import Data.Array (listArray, elems)
main :: IO ()
main = mapM_ print $ [sum, product] <*> [elems $ listArray (1, 10) [11 .. 20]]
- Output:
155 670442572800
HicEst
array = $ ! 1, 2, ..., LEN(array)
sum = SUM(array)
product = 1 ! no built-in product function in HicEst
DO i = 1, LEN(array)
product = product * array(i)
ENDDO
WRITE(ClipBoard, Name) n, sum, product ! n=100; sum=5050; product=9.33262154E157;
Icon and Unicon
The program below prints the sum and product of the arguments to the program.
IDL
array = [3,6,8]
print,total(array)
print,product(array)
Inform 7
Sum And Product is a room.
To decide which number is the sum of (N - number) and (M - number) (this is summing):
decide on N + M.
To decide which number is the product of (N - number) and (M - number) (this is production):
decide on N * M.
When play begins:
let L be {1, 2, 3, 4, 5};
say "List: [L in brace notation], sum = [summing reduction of L], product = [production reduction of L].";
end the story.
J
Simple approach:
(+/,*/) 2 3 5 7
17 210
Longer exposition:
sum =: +/
product =: */
For example:
sum 1 3 5 7 9 11 13
49
product 1 3 5 7 9 11 13
135135
a=: 3 10 ?@$ 100 NB. random array
a
90 47 58 29 22 32 55 5 55 73
58 50 40 5 69 46 34 40 46 84
29 8 75 97 24 40 21 82 77 9
NB. on a table, each row is an item to be summed:
sum a
177 105 173 131 115 118 110 127 178 166
product a
151380 18800 174000 14065 36432 58880 39270 16400 194810 55188
NB. but we can tell J to sum everything within each row, instead:
sum"1 a
466 472 462
product"1 a
5.53041e15 9.67411e15 1.93356e15
Java
public class SumProd
{
public static void main(final String[] args)
{
int sum = 0;
int prod = 1;
int[] arg = {1,2,3,4,5};
for (int i : arg)
{
sum += i;
prod *= i;
}
}
}
import java.util.Arrays;
public class SumProd
{
public static void main(final String[] args)
{
int[] arg = {1,2,3,4,5};
System.out.printf("sum = %d\n", Arrays.stream(arg).sum());
System.out.printf("sum = %d\n", Arrays.stream(arg).reduce(0, (a, b) -> a + b));
System.out.printf("product = %d\n", Arrays.stream(arg).reduce(1, (a, b) -> a * b));
}
}
- Output:
sum = 15 sum = 15 product = 120
JavaScript
ES5
var array = [1, 2, 3, 4, 5],
sum = 0,
prod = 1,
i;
for (i = 0; i < array.length; i += 1) {
sum += array[i];
prod *= array[i];
}
alert(sum + ' ' + prod);
Where supported, the reduce method can also be used:
var array = [1, 2, 3, 4, 5],
sum = array.reduce(function (a, b) {
return a + b;
}, 0),
prod = array.reduce(function (a, b) {
return a * b;
}, 1);
alert(sum + ' ' + prod);
ES6
(() => {
'use strict';
// sum :: (Num a) => [a] -> a
const sum = xs => xs.reduce((a, x) => a + x, 0);
// product :: (Num a) => [a] -> a
const product = xs => xs.reduce((a, x) => a * x, 1);
// TEST
// show :: a -> String
const show = x => JSON.stringify(x, null, 2);
return show(
[sum, product]
.map(f => f([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]))
);
})();
- Output:
[ 55, 3628800 ]
Joy
[1 2 3 4 5] 0 [+] fold.
[1 2 3 4 5] 1 [*] fold.
jq
The builtin filter, add/0, computes the sum of an array:
[4,6,8] | add
# => 18
[range(2;5) * 2] | add
# => 18
An efficient companion filter for computing the product of the items in an array can be defined as follows:
def prod: reduce .[] as $i (1; . * $i);
Examples:
[4,6,8] | prod
# => 192
10!
[range(1;11)] | prod
# =>3628800
Julia
julia> sum([4,6,8])
18
julia> +((1:10)...)
55
julia +([1,2,3]...)
6
julia> prod([4,6,8])
192
K
sum: {+/}x
product: {*/}x
a: 1 3 5 7 9 11 13
sum a
49
product a
135135
It is easy to see the relationship of K to J here.
Kotlin
// version 1.1.2
fun main(args: Array<String>) {
val a = intArrayOf(1, 5, 8, 11, 15)
println("Array contains : ${a.contentToString()}")
val sum = a.sum()
println("Sum is $sum")
val product = a.fold(1) { acc, i -> acc * i }
println("Product is $product")
}
- Output:
Array contains : [1, 5, 8, 11, 15] Sum is 40 Product is 6600
Lambdatalk
{A.serie start end [step]} creates a sequence from start to end with optional step
{A.new words} creates an array from a sequence of words
{A.toS array} creates a sequence from the items of an array
{long_add x y} returns the sum of two integers of any size
{long_mult x y} returns the product of two integers of any size
{def A {A.new {S.serie 1 10}}} -> [1,2,3,4,5,6,7,8,9,10]
{+ {A.toS {A}}} -> 55
{* {A.toS {A}}} -> 3628800
{def B {A.new {S.serie 1 100}}} -> [1,2,3,4,5,6,7,8,9,10,...,95,96,97,98,99,100]
{S.reduce long_add {A.toS {B}}} -> 5050
{S.reduce long_mult {A.toS {B}}} ->
9332621544394415268169923885626670049071596826438162146859296389521759999322991
5608941463976156518286253697920827223758251185210916864000000000000000000000000
Lang
&values = fn.arrayGenerateFrom(fn.inc, 5)
fn.println(fn.arrayReduce(&values, 0, fn.add))
# Output: 15
fn.println(fn.arrayReduce(&values, 1, fn.mul))
# Output: 120
Lang5
4 iota 1 + dup
'+ reduce
'* reduce
langur
val .list = series 19
writeln " list: ", .list
writeln " sum: ", fold fn{+}, .list
writeln "product: ", fold fn{*}, .list
- Output:
list: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19] sum: 190 product: 121645100408832000
Lasso
local(x = array(1,2,3,4,5,6,7,8,9,10))
// sum of array elements
'Sum: '
with n in #x
sum #n
'\r'
// product of arrray elements
'Product: '
local(product = 1)
with n in #x do => { #product *= #n }
#product
- Output:
Sum: 55 Product: 3628800
Liberty BASIC
Dim array(19)
For i = 0 To 19
array(i) = Int(Rnd(1) * 20)
Next i
'product must first equal one or you will get 0 as the product
product = 1
For i = 0 To 19
sum = (sum + array(i))
product = (product * array(i))
next i
Print "Sum is " + str$(sum)
Print "Product is " + str$(product)
Lingo
on sum (intList)
res = 0
repeat with v in intList
res = res + v
end repeat
return res
end
on product (intList)
res = 1
repeat with v in intList
res = res * v
end repeat
return res
end
LiveCode
//sum
put "1,2,3,4" into nums
split nums using comma
answer sum(nums)
// product
local prodNums
repeat for each element n in nums
if prodNums is empty then
put n into prodNums
else
multiply prodnums by n
end if
end repeat
answer prodnums
Logo
print apply "sum arraytolist {1 2 3 4 5}
print apply "product arraytolist {1 2 3 4 5}
LOLCODE
HAI 1.2
I HAS A Nums ITZ A BUKKIT
Nums HAS A Length ITZ 0
Nums HAS A SRS Nums'Z Length ITZ 1
Nums'Z Length R SUM OF Nums'Z Length AN 1
Nums HAS A SRS Nums'Z Length ITZ 2
Nums'Z Length R SUM OF Nums'Z Length AN 1
Nums HAS A SRS Nums'Z Length ITZ 3
Nums'Z Length R SUM OF Nums'Z Length AN 1
Nums HAS A SRS Nums'Z Length ITZ 5
Nums'Z Length R SUM OF Nums'Z Length AN 1
Nums HAS A SRS Nums'Z Length ITZ 7
Nums'Z Length R SUM OF Nums'Z Length AN 1
I HAS A Added ITZ 0
I HAS A Timesed ITZ 1
I HAS A Num
IM IN YR Loop UPPIN YR Index WILE DIFFRINT Index AN Nums'Z Length
Num R Nums'Z SRS Index
Added R SUM OF Added AN Num
Timesed R PRODUKT OF Timesed AN Num
IM OUTTA YR Loop
VISIBLE "Sum = " !
VISIBLE Added
VISIBLE "Product = " !
VISIBLE Timesed
KTHXBYE
- Output:
Sum = 18 Product = 210
Lua
function sumf(a, ...) return a and a + sumf(...) or 0 end
function sumt(t) return sumf(unpack(t)) end
function prodf(a, ...) return a and a * prodf(...) or 1 end
function prodt(t) return prodf(unpack(t)) end
print(sumt{1, 2, 3, 4, 5})
print(prodt{1, 2, 3, 4, 5})
function table.sum(arr, length)
--same as if <> then <> else <>
return length == 1 and arr[1] or arr[length] + table.sum(arr, length -1)
end
function table.product(arr, length)
return length == 1 and arr[1] or arr[length] * table.product(arr, length -1)
end
t = {1,2,3}
print(table.sum(t,#t))
print(table.product(t,3))
Lucid
prints a running sum and product of sequence 1,2,3...
[%sum,product%]
where
x = 1 fby x + 1;
sum = 0 fby sum + x;
product = 1 fby product * x
end
M2000 Interpreter
Module Checkit {
a = (1,2,3,4,5,6,7,8,9,10)
print a#sum() = 55
sum = lambda->{push number+number}
product = lambda->{Push number*number}
print a#fold(lambda->{Push number*number}, 1), a#fold(lambda->{push number+number},0)
dim a(2,2) = 5
Print a()#sum() = 20
}
checkit
Maple
a := Array([1, 2, 3, 4, 5, 6]);
add(a);
mul(a);
Mathematica/Wolfram Language
Mathematica provides many ways of doing the sum of an array (any kind of numbers or symbols):
a = {1, 2, 3, 4, 5}
Plus @@ a
Apply[Plus, a]
Total[a]
Total@a
a // Total
Sum[a[[i]], {i, 1, Length[a]}]
Sum[i, {i, a}]
all give 15. For product we also have a couple of choices:
a = {1, 2, 3, 4, 5}
Times @@ a
Apply[Times, a]
Product[a[[i]], {i, 1, Length[a]}]
Product[i, {i, a}]
all give 120.
MATLAB
These two function are built into MATLAB as the "sum(array)" and "prod(array)" functions.
Sample Usage:
>> array = [1 2 3;4 5 6;7 8 9]
array =
1 2 3
4 5 6
7 8 9
>> sum(array,1)
ans =
12 15 18
>> sum(array,2)
ans =
6
15
24
>> prod(array,1)
ans =
28 80 162
>> prod(array,2)
ans =
6
120
504
Maxima
lreduce("+", [1, 2, 3, 4, 5, 6, 7, 8]);
36
lreduce("*", [1, 2, 3, 4, 5, 6, 7, 8]);
40320
MAXScript
arr = #(1, 2, 3, 4, 5)
sum = 0
for i in arr do sum += i
product = 1
for i in arr do product *= i
min
(1 2 3 4 5) ((sum) (1 '* reduce)) cleave
"Sum: $1\nProduct: $2" get-stack % puts
- Output:
Sum: 15 Product: 120
МК-61/52
^ 1 ПE + П0 КИП0 x#0 18 ^ ИПD
+ ПD <-> ИПE * ПE БП 05 С/П
Instruction: РX - array length, Р1:РC - array, РD and РE - sum and product of an array.
Modula-3
MODULE Sumprod EXPORTS Main;
FROM IO IMPORT Put;
FROM Fmt IMPORT Int;
VAR a := ARRAY [1..5] OF INTEGER {1, 2, 3, 4, 5};
VAR sum: INTEGER := 0;
VAR prod: INTEGER := 1;
BEGIN
FOR i := FIRST(a) TO LAST(a) DO
INC(sum, a[i]);
prod := prod * a[i];
END;
Put("Sum of array: " & Int(sum) & "\n");
Put("Product of array: " & Int(prod) & "\n");
END Sumprod.
- Output:
Sum of array: 15 Product of array: 120
MUMPS
SUMPROD(A)
;Compute the sum and product of the numbers in the array A
NEW SUM,PROD,POS
;SUM is the running sum,
;PROD is the running product,
;POS is the position within the array A
SET SUM=0,PROD=1,POS=""
FOR SET POS=$ORDER(A(POS)) Q:POS="" SET SUM=SUM+A(POS),PROD=PROD*A(POS)
WRITE !,"The sum of the array is "_SUM
WRITE !,"The product of the array is "_PROD
KILL SUM,PROD,POS
QUIT
Example:
USER>SET C(-1)=2,C("A")=3,C(42)=1,C(0)=7 USER>D SUMPROD^ROSETTA(.C) The sum of the array is 13 The product of the array is 42
Note - the string "A" converts to 0 when doing mathematical operations.
USER>SET C(-1)=2,C("A")="3H",C(42)=.1,C(0)=7.0,C("B")="A" USER>D SUMPROD^ROSETTA(.C) The sum of the array is 12.1 The product of the array is 0
Nemerle
As mentioned for some of the other functional languages, it seems more natural to work with lists in Nemerle, but as the task specifies working on an array, this solution will work on either.
using System;
using System.Console;
using System.Collections.Generic;
using Nemerle.Collections;
module SumProd
{
Sum[T] (nums : T) : int
where T : IEnumerable[int]
{
nums.FoldLeft(0, _+_)
}
Product[T] (nums : T) : int
where T : IEnumerable[int]
{
nums.FoldLeft(1, _*_)
}
Main() : void
{
def arr = array[1, 2, 3, 4, 5];
def lis = [1, 2, 3, 4, 5];
def suml = Sum(lis);
def proda = Product(arr);
WriteLine("Sum is: {0}\tProduct is: {1}", suml, proda);
}
}
NetRexx
/* NetRexx */
options replace format comments java crossref savelog symbols binary
harry = [long 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
sum = long 0
product = long 1
entries = Rexx ''
loop n_ = int 0 to harry.length - 1
nxt = harry[n_]
entries = entries nxt
sum = sum + nxt
product = product * nxt
end n_
entries = entries.strip
say 'Sum and product of' entries.changestr(' ', ',')':'
say ' Sum:' sum
say ' Product:' product
return
- Output:
Sum and product of 1,2,3,4,5,6,7,8,9,10: Sum: 55 Product: 3628800
NewLISP
(setq a '(1 2 3 4 5))
(apply + a)
(apply * a)
Nial
Nial being an array language, what applies to individual elements are extended to cover array operations by default strand notation
+ 1 2 3
= 6
* 1 2 3
= 6
array notation
+ [1,2,3]
grouped notation
(* 1 2 3)
= 6
* (1 2 3)
= 6
(All these notations are equivalent)
Nim
var xs = [1, 2, 3, 4, 5, 6]
var sum, product: int
product = 1
for x in xs:
sum += x
product *= x
Or functionally:
import sequtils
let
xs = [1, 2, 3, 4, 5, 6]
sum = xs.foldl(a + b)
product = xs.foldl(a * b)
Or using a math function:
import math
let numbers = [1, 5, 4]
let total = sum(numbers)
var product = 1
for n in numbers:
product *= n
Objeck
sum := 0;
prod := 1;
arg := [1, 2, 3, 4, 5];
each(i : arg) {
sum += arg[i];
prod *= arg[i];
};
Objective-C
Sum:
- (float) sum:(NSMutableArray *)array
{
int i, sum, value;
sum = 0;
value = 0;
for (i = 0; i < [array count]; i++) {
value = [[array objectAtIndex: i] intValue];
sum += value;
}
return suml;
}
Product:
- (float) prod:(NSMutableArray *)array
{
int i, prod, value;
prod = 0;
value = 0;
for (i = 0; i < [array count]; i++) {
value = [[array objectAtIndex: i] intValue];
prod *= value;
}
return suml;
}
OCaml
Arrays
(* ints *)
let a = [| 1; 2; 3; 4; 5 |];;
Array.fold_left (+) 0 a;;
Array.fold_left ( * ) 1 a;;
(* floats *)
let a = [| 1.0; 2.0; 3.0; 4.0; 5.0 |];;
Array.fold_left (+.) 0.0 a;;
Array.fold_left ( *.) 1.0 a;;
Lists
(* ints *)
let x = [1; 2; 3; 4; 5];;
List.fold_left (+) 0 x;;
List.fold_left ( * ) 1 x;;
(* floats *)
let x = [1.0; 2.0; 3.0; 4.0; 5.0];;
List.fold_left (+.) 0.0 x;;
List.fold_left ( *.) 1.0 x;;
Octave
a = [ 1, 2, 3, 4, 5, 6 ];
b = [ 10, 20, 30, 40, 50, 60 ];
vsum = a + b;
vprod = a .* b;
Oforth
[1, 2, 3, 4, 5 ] sum println
[1, 3, 5, 7, 9 ] prod println
- Output:
15 945
Ol
(print (fold + 0 '(1 2 3 4 5)))
(print (fold * 1 '(1 2 3 4 5)))
ooRexx
a=.my_array~new(20)
do i=1 To 20
a[i]=i
End
s=a~makestring((LINE),',')
Say s
Say ' sum='a~sum
Say 'product='a~prod
::class my_array subclass array
::method sum
sum=0
Do i=1 To self~dimension(1)
sum+=self[i]
End
Return sum
::method prod
Numeric Digits 30
prod=1
Do i=1 To self~dimension(1)
prod*=self[i]
End
Return prod
- Output:
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20 sum=210 product=2432902008176640000
Oz
Calculations like this are typically done on lists, not on arrays:
declare
Xs = [1 2 3 4 5]
Sum = {FoldL Xs Number.'+' 0}
Product = {FoldL Xs Number.'*' 1}
in
{Show Sum}
{Show Product}
If you are actually working with arrays, a more imperative approach seems natural:
declare
Arr = {Array.new 1 3 0}
Sum = {NewCell 0}
in
Arr.1 := 1
Arr.2 := 2
Arr.3 := 3
for I in {Array.low Arr}..{Array.high Arr} do
Sum := @Sum + Arr.I
end
{Show @Sum}
PARI/GP
These are built in to GP: vecsum
and factorback
(the latter can also take factorization matrices, thus the name). They could be coded like so:
vecsum1(v)={
sum(i=1,#v,v[i])
};
vecprod(v)={
prod(i=1,#v,v[i])
};
In 2.10.0 the function vecprod
was introduced as well. Like factorback
it gives the product of the elements of an array but unlike factorback
it doesn't handle factorization matrices.
Pascal
See Delphi
Perl
my @list = ( 1, 2, 3 );
my ( $sum, $prod ) = ( 0, 1 );
$sum += $_ foreach @list;
$prod *= $_ foreach @list;
Or using the List::Util module:
use List::Util qw/sum0 product/;
my @list = (1..9);
say "Sum: ", sum0(@list); # sum0 returns 0 for an empty list
say "Product: ", product(@list);
- Output:
Sum: 45 Product: 362880
Phix
sequence s = {1,2,3,4,5} printf(1,"sum is %d\n",sum(s)) printf(1,"prod is %d\n",product(s))
- Output:
sum is 15 prod is 120
Phixmonti
include ..\Utilitys.pmt
( 1 2 3 4 5 )
dup sum "sum is " print print nl
1 swap
len for
get rot * swap
endfor
drop
"mult is " print print nl
PHP
$array = array(1,2,3,4,5,6,7,8,9);
echo array_sum($array);
echo array_product($array);
Picat
go =>
L = 1..10,
println(sum=sum(L)),
println(prod=prod(L)),
nl,
println(sum_reduce=reduce(+,L)),
println(prod_reduce=reduce(*,L)),
println(sum_reduce=reduce(+,L,0)),
println(prod_reduce=reduce(*,L,1)),
nl,
println(sum_fold=fold(+,0,L)),
println(prod_fold=fold(*,1,L)),
nl,
println(sum_rec=sum_rec(L)),
println(prod_rec=prod_rec(L)),
nl.
% recursive variants
sum_rec(List) = Sum =>
sum_rec(List,0,Sum).
sum_rec([],Sum0,Sum) =>
Sum=Sum0.
sum_rec([H|T], Sum0,Sum) =>
sum_rec(T, H+Sum0,Sum).
prod_rec(List) = Prod =>
prod_rec(List,1,Prod).
prod_rec([],Prod0,Prod) =>
Prod=Prod0.
prod_rec([H|T], Prod0,Prod) =>
prod_rec(T, H*Prod0,Prod).
- Output:
sum = 55 prod = 3628800 sum_reduce = 55 prod_reduce = 3628800 sum_reduce = 55 prod_reduce = 3628800 sum_fold = 55 prod_fold = 3628800 sum_rec = 55 prod_rec = 3628800
PicoLisp
(let Data (1 2 3 4 5)
(cons
(apply + Data)
(apply * Data) ) )
- Output:
(15 . 120)
PL/I
declare A(10) fixed binary static initial
(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
put skip list (sum(A));
put skip list (prod(A));
Plain English
An element is a thing with a number.
To find a sum and a product of some elements:
Put 0 into the sum.
Put 1 into the product.
Get an element from the elements.
Loop.
If the element is nil, exit.
Add the element's number to the sum.
Multiply the product by the element's number.
Put the element's next into the element.
Repeat.
To make some example elements:
If a counter is past 10, exit.
Allocate memory for an element.
Put the counter into the element's number.
Append the element to the example.
Repeat.
A product is a number.
To run:
Start up.
Make some example elements.
Find a sum and a product of the example elements.
Destroy the example elements.
Write "Sum: " then the sum on the console.
Write "Product: " then the product on the console.
Wait for the escape key.
Shut down.
A sum is a number.
- Output:
Sum: 55 Product: 3628800
Pop11
Simple loop:
lvars i, sum = 0, prod = 1, ar = {1 2 3 4 5 6 7 8 9};
for i from 1 to length(ar) do
ar(i) + sum -> sum;
ar(i) * prod -> prod;
endfor;
One can alternatively use second order iterator:
lvars sum = 0, prod = 1, ar = {1 2 3 4 5 6 7 8 9};
appdata(ar, procedure(x); x + sum -> sum; endprocedure);
appdata(ar, procedure(x); x * prod -> prod; endprocedure);
PostScript
/sumandproduct
{
/x exch def
/sum 0 def
/prod 0 def
/i 0 def
x length 0 eq
{
}
{
/prod prod 1 add def
x length{
/sum sum x i get add def
/prod prod x i get mul def
/i i 1 add def
}repeat
}ifelse
sum ==
prod ==
}def
% sum
[1 1 1 1 1] 0 {add} fold
% product
[1 1 1 1 1] 1 {mul} fold
PowerShell
The Measure-Object
cmdlet already knows how to compute a sum:
function Get-Sum ($a) {
return ($a | Measure-Object -Sum).Sum
}
But not how to compute a product:
function Get-Product ($a) {
if ($a.Length -eq 0) {
return 0
} else {
$p = 1
foreach ($x in $a) {
$p *= $x
}
return $p
}
}
One could also let PowerShell do all the work by simply creating an expression to evaluate:
function Get-Product ($a) {
if ($a.Length -eq 0) {
return 0
}
$s = $a -join '*'
return (Invoke-Expression $s)
}
Even nicer, however, is a function which computes both at once and returns a custom object with appropriate properties:
function Get-SumAndProduct ($a) {
$sum = 0
if ($a.Length -eq 0) {
$prod = 0
} else {
$prod = 1
foreach ($x in $a) {
$sum += $x
$prod *= $x
}
}
$ret = New-Object PSObject
$ret | Add-Member NoteProperty Sum $sum
$ret | Add-Member NoteProperty Product $prod
return $ret
}
- Output:
PS> Get-SumAndProduct 5,9,7,2,3,8,4 Sum Product --- ------- 38 60480
Prolog
sum([],0).
sum([H|T],X) :- sum(T,Y), X is H + Y.
product([],1).
product([H|T],X) :- product(T,Y), X is H * X.
test
:- sum([1,2,3,4,5,6,7,8,9],X). X =45; :- product([1,2,3,4,5],X). X = 120;
Using fold
add(A,B,R):-
R is A + B.
mul(A,B,R):-
R is A * B.
% define fold now.
fold([], Act, Init, Init).
fold(Lst, Act, Init, Res):-
head(Lst,Hd),
tail(Lst,Tl),
apply(Act,[Init, Hd, Ra]),
fold(Tl, Act, Ra, Res).
sumproduct(Lst, Sum, Prod):-
fold(Lst,mul,1, Prod),
fold(Lst,add,0, Sum).
?- sumproduct([1,2,3,4],Sum,Prod).
Sum = 10,
Prod = 24 .
PureBasic
Dim MyArray(9)
Define a, sum=0, prod=1
For a = 0 To ArraySize(MyArray()) ; Create a list of some random numbers
MyArray(a) = 1 + Random(9) ; Insert a number [1...10] in current element
Next
For a = 0 To ArraySize(MyArray()) ; Calculate Sum and Product of this Array
sum + MyArray(a)
prod * MyArray(a)
Next
Debug "The sum is " + Str(sum) ; Present the results
Debug "Product is " + Str(prod)
Python
numbers = [1, 2, 3]
total = sum(numbers)
product = 1
for i in numbers:
product *= i
Or functionally (faster but perhaps less clear):
from operator import mul, add
sum = reduce(add, numbers) # note: this version doesn't work with empty lists
sum = reduce(add, numbers, 0)
product = reduce(mul, numbers) # note: this version doesn't work with empty lists
product = reduce(mul, numbers, 1)
from numpy import r_
numbers = r_[1:4]
total = numbers.sum()
product = numbers.prod()
If you are summing floats in Python 2.6+, you should use math.fsum() to avoid loss of precision:
import math
total = math.fsum(floats)
QBasic
DIM array(1 TO 5)
DATA 1, 2, 3, 4, 5
FOR index = LBOUND(array) TO UBOUND(array)
READ array(index)
NEXT index
LET sum = 0
LET prod = 1
FOR index = LBOUND(array) TO UBOUND(array)
LET sum = sum + array(index)
LET prod = prod * array(index)
NEXT index
PRINT "The sum is "; sum
PRINT "and the product is "; prod
END
Quackery
[ 0 swap witheach + ] is sum ( [ --> n )
[ 1 swap witheach * ] is product ( [ --> n )
In the shell (i.e. Quackery REPL):
/O> ' [ 1 2 3 4 5 ] sum echo cr
... ' [ 1 2 3 4 5 ] product echo
...
15
120
Stack empty.
R
total <- sum(1:5)
product <- prod(1:5)
Racket
#lang racket
(for/sum ([x #(3 1 4 1 5 9)]) x)
(for/product ([x #(3 1 4 1 5 9)]) x)
Raku
(formerly Perl 6)
my @ary = 1, 5, 10, 100;
say 'Sum: ', [+] @ary;
say 'Product: ', [*] @ary;
Rapira
fun sumOfArr(arr)
sum := 0
for N from 1 to #arr do
sum := sum + arr[N]
od
return sum
end
fun productOfArr(arr)
product := arr[1]
for N from 2 to #arr do
product := product * arr[N]
od
return product
end
Raven
0 [ 1 2 3 ] each +
1 [ 1 2 3 ] each *
REBOL
REBOL [
Title: "Sum and Product"
URL: http://rosettacode.org/wiki/Sum_and_product_of_array
]
; Simple:
sum: func [a [block!] /local x] [x: 0 forall a [x: x + a/1] x]
product: func [a [block!] /local x] [x: 1 forall a [x: x * a/1] x]
; Way too fancy:
redux: func [
"Applies an operation across an array to produce a reduced value."
a [block!] "Array to operate on."
op [word!] "Operation to perform."
/init x "Initial value (default 0)."
][if not init [x: 0] forall a [x: do compose [x (op) (a/1)]] x]
rsum: func [a [block!]][redux a '+]
rproduct: func [a [block!]][redux/init a '* 1]
; Tests:
assert: func [code][print [either do code [" ok"]["FAIL"] mold code]]
print "Simple dedicated functions:"
assert [55 = sum [1 2 3 4 5 6 7 8 9 10]]
assert [3628800 = product [1 2 3 4 5 6 7 8 9 10]]
print [crlf "Fancy reducing function:"]
assert [55 = rsum [1 2 3 4 5 6 7 8 9 10]]
assert [3628800 = rproduct [1 2 3 4 5 6 7 8 9 10]]
- Output:
Simple dedicated functions: ok [55 = sum [1 2 3 4 5 6 7 8 9 10]] ok [3628800 = product [1 2 3 4 5 6 7 8 9 10]] Fancy reducing function: ok [55 = rsum [1 2 3 4 5 6 7 8 9 10]] ok [3628800 = rproduct [1 2 3 4 5 6 7 8 9 10]]
Red
Red [
red-version: 0.6.4
description: "Find the sum and product of an array of numbers."
]
product: function [
"Returns the product of all values in a block."
values [any-list! vector!]
][
result: 1
foreach value values [result: result * value]
result
]
a: [1 2 3 4 5 6 7 8 9 10]
print a
print ["Sum:" sum a]
print ["Product:" product a]
- Output:
1 2 3 4 5 6 7 8 9 10 Sum: 55 Product: 3628800
REXX
/*REXX program adds and multiplies N elements of a (populated) array @. */
numeric digits 200 /*200 decimal digit #s (default is 9).*/
parse arg N .; if N=='' then N=20 /*Not specified? Then use the default.*/
do j=1 for N /*build array of N elements (or 20?).*/
@.j=j /*set 1st to 1, 3rd to 3, 8th to 8 ··· */
end /*j*/
sum=0 /*initialize SUM (variable) to zero. */
prod=1 /*initialize PROD (variable) to unity.*/
do k=1 for N
sum = sum + @.k /*add the element to the running total.*/
prod = prod * @.k /*multiply element to running product. */
end /*k*/ /* [↑] this pgm: same as N factorial.*/
say ' sum of ' m " elements for the @ array is: " sum
say ' product of ' m " elements for the @ array is: " prod
/*stick a fork in it, we're all done. */
output using the default input of: 20
sum of M elements for the @ array is: 210 product of M elements for the @ array is: 2432902008176640000
Ring
aList = 1:10 nSum=0 nProduct=0
for x in aList nSum += x nProduct *= x next
See "Sum = " + nSum + nl
See "Product = " + nProduct + nl
RPL
≪ DUP DUP 1 CON DOT SWAP ARRY→ LIST→ SWAP 1 - START * NEXT ≫ 'SUMPR' STO [ 2 4 8 -5 ] SUMPR
- Output:
2: 9 1: -320
Ruby
arr = [1,2,3,4,5] # or ary = *1..5, or ary = (1..5).to_a
p sum = arr.inject(0) { |sum, item| sum + item }
# => 15
p product = arr.inject(1) { |prod, element| prod * element }
# => 120
arr = [1,2,3,4,5]
p sum = arr.inject(0, :+) #=> 15
p product = arr.inject(1, :*) #=> 120
# If you do not explicitly specify an initial value for memo,
# then the first element of collection is used as the initial value of memo.
p sum = arr.inject(:+) #=> 15
p product = arr.inject(:*) #=> 120
Note: When the Array is empty, the initial value returns. However, nil returns if not giving an initial value.
arr = []
p arr.inject(0, :+) #=> 0
p arr.inject(1, :*) #=> 1
p arr.inject(:+) #=> nil
p arr.inject(:*) #=> nil
Enumerable#reduce is the alias of Enumerable#inject.
arr = [1,2,3,4,5]
p sum = arr.sum #=> 15
p [].sum #=> 0
Run BASIC
dim array(100)
for i = 1 To 100
array(i) = rnd(0) * 100
next i
product = 1
for i = 0 To 19
sum = (sum + array(i))
product = (product * array(i))
next i
Print " Sum is ";sum
Print "Product is ";product
Rust
fn main() {
let arr = vec![1, 2, 3, 4, 5, 6, 7, 8, 9];
// using fold
let sum = arr.iter().fold(0i32, |a, &b| a + b);
let product = arr.iter().fold(1i32, |a, &b| a * b);
println!("the sum is {} and the product is {}", sum, product);
// or using sum and product
let sum = arr.iter().sum::<i32>();
let product = arr.iter().product::<i32>();
println!("the sum is {} and the product is {}", sum, product);
}
S-lang
variable a = [5, -2, 3, 4, 666, 7];
The sum of array elements is handled by an intrinsic. [note: print is slsh-specific; if not available, use printf().]
print(sum(a));
The product is slightly more involved; I'll use this as a chance to show the alternate stack-based use of 'foreach':
variable prod = a[0];
% Skipping the loop variable causes the val to be placed on the stack.
% Also note that the double-brackets ARE required. The inner one creates
% a "range array" based on the length of a.
foreach (a[[1:]])
% () pops it off.
prod *= ();
print(prod);
SAS
data _null_;
array a{*} a1-a100;
do i=1 to 100;
a{i}=i*i;
end;
b=sum(of a{*});
put b c;
run;
Sather
class MAIN is
main is
a :ARRAY{INT} := |10, 5, 5, 20, 60, 100|;
sum, prod :INT;
loop sum := sum + a.elt!; end;
prod := 1;
loop prod := prod * a.elt!; end;
#OUT + sum + " " + prod + "\n";
end;
end;
Scala
val seq = Seq(1, 2, 3, 4, 5)
val sum = seq.foldLeft(0)(_ + _)
val product = seq.foldLeft(1)(_ * _)
Or even shorter:
val sum = seq.sum
val product = seq.product
Works with all data types for which a Numeric implicit is available.
Scheme
(apply + '(1 2 3 4 5))
(apply * '(1 2 3 4 5))
A tail-recursive solution, without the n-ary operator "trick". Because Scheme supports tail call optimization, this is as space-efficient as an imperative loop.
(define (reduce f i l)
(if (null? l)
i
(reduce f (f i (car l)) (cdr l))))
(reduce + 0 '(1 2 3 4 5)) ;; 0 is unit for +
(reduce * 1 '(1 2 3 4 5)) ;; 1 is unit for *
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;
const func integer: prodArray (in array integer: valueArray) is func
result
var integer: prod is 1;
local
var integer: value is 0;
begin
for value range valueArray do
prod *:= value;
end for;
end func;
Call these functions with:
writeln(sumArray([](1, 2, 3, 4, 5))); writeln(prodArray([](1, 2, 3, 4, 5)));
SETL
numbers := [1 2 3 4 5 6 7 8 9];
print(+/ numbers, */ numbers);
=> 45 362880
Sidef
Using built-in methods:
var ary = [1, 2, 3, 4, 5];
say ary.sum; # => 15
say ary.prod; # => 120
Alternatively, using hyper-operators:
var ary = [1, 2, 3, 4, 5];
say ary«+»; # => 15
say ary«*»; # => 120
Slate
#(1 2 3 4 5) reduce: [:sum :number | sum + number]
#(1 2 3 4 5) reduce: [:product :number | product * number]
Shorthand for the above with a macro:
#(1 2 3 4 5) reduce: #+ `er
#(1 2 3 4 5) reduce: #* `er
Smalltalk
#(1 2 3 4 5) inject: 0 into: [:sum :number | sum + number]
#(1 2 3 4 5) inject: 1 into: [:product :number | product * number]
Some implementation also provide a fold: message:
#(1 2 3 4 5) fold: [:sum :number | sum + number]
#(1 2 3 4 5) fold: [:product :number | product * number]
SNOBOL4
t = table()
* read the integer from the std. input
init_tab t<x = x + 1> = trim(input) :s(init_tab)
product = 1
sum = 0
* counting backwards to 1
loop i = t< x = ?gt(x,1) x - 1> :f(out)
sum = sum + i
product = product * i :(loop)
out output = "Sum: " sum
output = "Prod: " product
end
Input
1 2 3 4 5
- Output:
Sum: 15 Prod: 120
SparForte
As a structured script.
#!/usr/local/bin/spar
pragma annotate( summary, "arraysum" )
@( description, "Compute the sum and product of an array of integers." )
@( see_also, "http://rosettacode.org/wiki/Sum_and_product_of_an_array" )
@( author, "Ken O. Burtch" );
pragma license( unrestricted );
pragma restriction( no_external_commands );
procedure arraysum is
type int_array is array(1..10) of integer;
myarr : int_array := (1,2,3,4,5,6,7,8,9,10 );
begin
? stats.sum( myarr );
declare
product : integer := 1;
begin
for i in arrays.first( myarr )..arrays.last( myarr ) loop
product := @ * myarr(i);
end loop;
? product;
end;
end arraysum;
Sparkling
spn:1> reduce({ 1, 2, 3, 4, 5 }, 0, function(x, y) { return x + y; })
= 15
spn:2> reduce({ 1, 2, 3, 4, 5 }, 1, function(x, y) { return x * y; })
= 120
Standard ML
Arrays
(* ints *)
val a = Array.fromList [1, 2, 3, 4, 5];
Array.foldl op+ 0 a;
Array.foldl op* 1 a;
(* reals *)
val a = Array.fromList [1.0, 2.0, 3.0, 4.0, 5.0];
Array.foldl op+ 0.0 a;
Array.foldl op* 1.0 a;
Lists
(* ints *)
val x = [1, 2, 3, 4, 5];
foldl op+ 0 x;
foldl op* 1 x;
(* reals *)
val x = [1.0, 2.0, 3.0, 4.0, 5.0];
foldl op+ 0.0 x;
foldl op* 1.0 x;
Stata
Mata does not have a builtin product function, but one can do the following, which will compute the product of nonzero elements of the array:
a = 1,-2,-3,-4,5
sum(a)
-3
(-1)^mod(sum(a:<0),2)*exp(sum(log(abs(a))))
-120
Swift
let a = [1, 2, 3, 4, 5]
println(a.reduce(0, +)) // prints 15
println(a.reduce(1, *)) // prints 120
println(reduce(a, 0, +)) // prints 15
println(reduce(a, 1, *)) // prints 120
Tcl
set arr [list 3 6 8]
set sum [expr [join $arr +]]
set prod [expr [join $arr *]]
set arr [list 3 6 8]
set sum [tcl::mathop::+ {*}$arr]
set prod [tcl::mathop::* {*}$arr]
TI-83 BASIC
Use the built-in functions sum()
and prod()
.
seq(X,X,1,10,1)→L₁
{1 2 3 4 5 6 7 8 9 10}
sum(L₁)
55
prod(L₁)
3628800
Toka
4 cells is-array foo
212 1 foo array.put
51 2 foo array.put
12 3 foo array.put
91 4 foo array.put
[ ( array size -- sum )
>r 0 r> 0 [ over i swap array.get + ] countedLoop nip ] is sum-array
( product )
reset 1 4 0 [ i foo array.get * ] countedLoop .
Trith
[1 2 3 4 5] 0 [+] foldl
[1 2 3 4 5] 1 [*] foldl
True BASIC
DIM array(1 TO 5)
DATA 1, 2, 3, 4, 5
FOR index = LBOUND(array) TO UBOUND(array)
READ array(index)
NEXT index
LET sum = 0
LET prod = 1
FOR index = LBOUND(array) TO UBOUND(array)
LET sum = sum + array(index)
LET prod = prod * array(index)
NEXT index
PRINT "The sum is "; sum
PRINT "and the product is "; prod
END
TUSCRIPT
$$ MODE TUSCRIPT
list="1'2'3'4'5"
sum=SUM(list)
PRINT " sum: ",sum
product=1
LOOP l=list
product=product*l
ENDLOOP
PRINT "product: ",product
- Output:
sum: 15 product: 120
UNIX Shell
From an internal variable, $IFS delimited:
sum=0
prod=1
list="1 2 3"
for n in $list
do sum="$(($sum + $n))"; prod="$(($prod * $n))"
done
echo $sum $prod
From the argument list (ARGV):
sum=0
prod=1
for n
do sum="$(($sum + $n))"; prod="$(($prod * $n))"
done
echo $sum $prod
From STDIN, one integer per line:
sum=0
prod=1
while read n
do sum="$(($sum + $n))"; prod="$(($prod * $n))"
done
echo $sum $prod
Using an actual array variable:
list=(20 20 2);
(( sum=0, prod=1 ))
for n in "${list[@]}"; do
(( sum += n, prod *= n ))
done
printf '%d\t%d\n' "$sum" "$prod"
- Output:
42 800
UnixPipes
Uses ksh93-style process substitution.
prod() {
(read B; res=$1; test -n "$B" && expr $res \* $B || echo $res)
}
sum() {
(read B; res=$1; test -n "$B" && expr $res + $B || echo $res)
}
fold() {
(func=$1; while read a ; do fold $func | $func $a ; done)
}
(echo 3; echo 1; echo 4;echo 1;echo 5;echo 9) |
tee >(fold sum) >(fold prod) > /dev/null
There is a race between fold sum
and fold prod
, which run in parallel. The program might print sum before product, or print product before sum.
Ursa
Ursa doesn't have arrays in the traditional sense. Its equivalent is the stream. All math operators take streams as arguments, so sums and products of streams can be found like this.
declare int<> stream
append 34 76 233 8 2 734 56 stream
# outputs 1143
out (+ stream) endl console
# outputs 3.95961079808E11
out (* stream) endl console
Ursala
The reduction operator, :-, takes an associative binary function and a constant for the empty case. Natural numbers are unsigned and of unlimited size.
#import nat
#cast %nW
sp = ^(sum:-0,product:-1) <62,43,46,40,29,55,51,82,59,92,48,73,93,35,42,25>
- Output:
(875,2126997171723931187788800000)
V
[sp dup 0 [+] fold 'product=' put puts 1 [*] fold 'sum=' put puts].
- Using it:
[1 2 3 4 5] sp
=
product=15
sum=120
Vala
void main() {
int sum = 0, prod = 1;
int[] data = { 1, 2, 3, 4 };
foreach (int val in data) {
sum += val;
prod *= val;
}
print(@"sum: $(sum)\nproduct: $(prod)");
}
- Output:
sum: 10 product: 24
VBA
Assumes Excel is used.
Sub Demo()
Dim arr
arr = Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
Debug.Print "sum : " & Application.WorksheetFunction.Sum(arr)
Debug.Print "product : " & Application.WorksheetFunction.Product(arr)
End Sub
- Output:
sum : 55 product : 3628800
VBScript
Function sum_and_product(arr)
sum = 0
product = 1
For i = 0 To UBound(arr)
sum = sum + arr(i)
product = product * arr(i)
Next
WScript.StdOut.Write "Sum: " & sum
WScript.StdOut.WriteLine
WScript.StdOut.Write "Product: " & product
WScript.StdOut.WriteLine
End Function
myarray = Array(1,2,3,4,5,6)
sum_and_product(myarray)
- Output:
Sum: 21 Product: 720
Visual Basic .NET
Module Program
Sub Main()
Dim arg As Integer() = {1, 2, 3, 4, 5}
Dim sum = arg.Sum()
Dim prod = arg.Aggregate(Function(runningProduct, nextFactor) runningProduct * nextFactor)
End Sub
End Module
V (Vlang)
fn main() {
values := [1, 2, 3, 4, 5]
mut sum, mut prod := 0, 1
for val in values {
sum += val
prod *= val
}
println("sum: $sum\nproduct: $prod")
}
- Output:
sum: 15 product: 120
Wart
def (sum_prod nums)
(list (+ @nums) (* @nums))
WDTE
let a => import 'arrays';
let s => import 'stream';
let sum array => a.stream array -> s.reduce 0 +;
let prod array => a.stream prod -> s.reduce 1 *;
Wortel
@sum [1 2 3 4] ; returns 10
@prod [1 2 3 4] ; returns 24
Wren
import "./math" for Nums
var a = [7, 10, 2, 4, 6, 1, 8, 3, 9, 5]
System.print("Array : %(a)")
System.print("Sum : %(Nums.sum(a))")
System.print("Product : %(Nums.prod(a))")
- Output:
Array : [7, 10, 2, 4, 6, 1, 8, 3, 9, 5] Sum : 55 Product : 3628800
XPL0
code CrLf=9, IntOut=11;
func SumProd(A, L);
int A, L;
int S, P, I;
[S:= 0; P:= 1;
for I:= 0 to L-1 do [S:= S+A(I); P:= P*A(I)];
IntOut(0, S); CrLf(0);
IntOut(0, P); CrLf(0);
]; \SumSq
SumProd([1,2,3,4,5,6,7,8,9,10], 10)
- Output:
55 3628800
XSLT
XSLT (or XPath rather) has a few built-in functions for reducing from a collection, but product is not among them. Because of referential transparency, one must resort to recursive solutions for general iterative operations upon collections. The following code represents the array by numeric values in <price> elements in the source document.
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" />
<xsl:template name="sum-prod">
<xsl:param name="values" />
<xsl:param name="sum" select="0" />
<xsl:param name="prod" select="1" />
<xsl:choose>
<xsl:when test="not($values)">
<xsl:text>
Sum: </xsl:text>
<xsl:value-of select="$sum" />
<xsl:text>
Product: </xsl:text>
<xsl:value-of select="$prod" />
</xsl:when>
<xsl:otherwise>
<xsl:call-template name="sum-prod">
<xsl:with-param name="values" select="$values[position() > 1]" />
<xsl:with-param name="sum" select="$sum + $values[1]" />
<xsl:with-param name="prod" select="$prod * $values[1]" />
</xsl:call-template>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
<xsl:template match="/">
<xsl:text>
Sum (built-in): </xsl:text>
<xsl:value-of select="sum(//price)" />
<xsl:call-template name="sum-prod">
<xsl:with-param name="values" select="//price" />
</xsl:call-template>
</xsl:template>
</xsl:stylesheet>
Yabasic
dim array(5)
data 1, 2, 3, 4, 5
for index = 1 to arraysize(array(), 1)
read array(index)
next index
sum = 0
prod = 1
for index = 1 to arraysize(array(), 1)
sum = sum + array(index)
prod = prod * array(index)
next index
print "The sum is ", sum //15
print "and the product is ", prod //120
end
Zig
const print = @import("std").debug.print;
pub fn main() void {
const numbers = [_]u8{ 1, 2, 3, 4, 5 };
var sum: u8 = 0;
var product: u8 = 1;
for (numbers) |number| {
product *= number;
sum += number;
}
print("{} {}\n", .{ product, sum });
}
zkl
fcn sum(vals){vals.reduce('+,0)}
fcn product(vals){vals.reduce('*,1)}
sum(T(1,2,3,4)) //-->10 product(T(1,2,3,4)) //-->24
Zoea
program: sum_and_product
case: 1
input: [3,5]
output: [8,15]
case: 2
input: [2,3,4]
output: [9,24]
Zoea Visual
- Programming Tasks
- Arithmetic operations
- Iteration
- 11l
- 360 Assembly
- 4D
- AArch64 Assembly
- ACL2
- Action!
- ActionScript
- Ada
- Aime
- ALGOL 68
- ALGOL W
- APL
- AppleScript
- ARM Assembly
- Arturo
- Asymptote
- AutoHotkey
- AWK
- Babel
- BASIC
- Applesoft BASIC
- Atari BASIC
- BaCon
- Chipmunk Basic
- BBC BASIC
- IS-BASIC
- BASIC256
- Bc
- Befunge
- BQN
- Bracmat
- Bruijn
- C
- C sharp
- C++
- STL
- Chef
- Clean
- Clojure
- CLU
- COBOL
- CoffeeScript
- ColdFusion
- Common Lisp
- Crystal
- D
- Dc
- Delphi
- E
- EasyLang
- Eiffel
- Elena
- Elixir
- Emacs Lisp
- Cl-lib
- Seq.el
- Erlang
- Euler
- Euphoria
- F Sharp
- Factor
- FALSE
- Fantom
- Fermat
- Forth
- Fortran
- FreeBASIC
- FreePascal
- Frink
- FutureBasic
- Fōrmulæ
- Gambas
- GAP
- GFA Basic
- Go
- Groovy
- GW-BASIC
- Haskell
- HicEst
- Icon
- Unicon
- IDL
- Inform 7
- J
- Java
- JavaScript
- Joy
- Jq
- Julia
- K
- Kotlin
- Lambdatalk
- Lang
- Lang5
- Langur
- Lasso
- Liberty BASIC
- Lingo
- LiveCode
- Logo
- LOLCODE
- Lua
- Lucid
- M2000 Interpreter
- Maple
- Mathematica
- Wolfram Language
- MATLAB
- Maxima
- MAXScript
- Min
- МК-61/52
- Modula-3
- MUMPS
- Nemerle
- NetRexx
- NewLISP
- Nial
- Nim
- Objeck
- Objective-C
- OCaml
- Octave
- Oforth
- Ol
- OoRexx
- Oz
- PARI/GP
- Pascal
- Perl
- Phix
- Phix/basics
- Phixmonti
- PHP
- Picat
- PicoLisp
- PL/I
- Plain English
- Pop11
- PostScript
- Initlib
- PowerShell
- Prolog
- PureBasic
- Python
- NumPy
- QBasic
- Quackery
- R
- Racket
- Raku
- Rapira
- Raven
- REBOL
- Red
- REXX
- Ring
- RPL
- Ruby
- Run BASIC
- Rust
- S-lang
- SAS
- Sather
- Scala
- Scheme
- Seed7
- SETL
- Sidef
- Slate
- Smalltalk
- SNOBOL4
- SparForte
- Sparkling
- Standard ML
- Stata
- Swift
- Tcl
- TI-83 BASIC
- Toka
- Trith
- True BASIC
- TUSCRIPT
- UNIX Shell
- UnixPipes
- Ursa
- Ursala
- V
- Vala
- VBA
- VBScript
- Visual Basic .NET
- V (Vlang)
- Wart
- WDTE
- Wortel
- Wren
- Wren-math
- XPL0
- XSLT
- Yabasic
- Zig
- Zkl
- Zoea
- Zoea Visual
- Pages with too many expensive parser function calls