Sum and product of an array: Difference between revisions

(Add CLU)
 
(43 intermediate revisions by 27 users not shown)
Line 7:
 
=={{header|11l}}==
<langsyntaxhighlight lang="11l">V arr = [1, 2, 3, 4]
print(sum(arr))
print(product(arr))</langsyntaxhighlight>
 
{{out}}
Line 18:
 
=={{header|360 Assembly}}==
<langsyntaxhighlight lang="360asm">* Sum and product of an array 20/04/2017
SUMPROD CSECT
USING SUMPROD,R15 base register
Line 38:
PG DS CL24 buffer
YREGS
END SUMPROD</langsyntaxhighlight>
{{out}}
<pre>
Line 45:
 
=={{header|4D}}==
<langsyntaxhighlight lang="4d">ARRAY INTEGER($list;0)
For ($i;1;5)
APPEND TO ARRAY($list;$i)
Line 60:
 
$sum:=sum($list)
</syntaxhighlight>
</lang>
=={{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}}==
<langsyntaxhighlight Lisplang="lisp">(defun sum (xs)
(if (endp xs)
0
Line 73 ⟶ 222:
1
(* (first xs)
(prod (rest xs)))))</langsyntaxhighlight>
 
=={{header|Action!}}==
<langsyntaxhighlight Actionlang="action!">DEFINE LAST="6"
 
PROC Main()
Line 110 ⟶ 259:
OD
PrintIE(res)
RETURN</langsyntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Sum_and_product_of_an_array.png Screenshot from Atari 8-bit computer]
Line 119 ⟶ 268:
 
=={{header|ActionScript}}==
<langsyntaxhighlight lang="actionscript">package {
import flash.display.Sprite;
 
Line 140 ⟶ 289:
}
}
}</langsyntaxhighlight>
 
=={{header|Ada}}==
<langsyntaxhighlight lang="ada">type Int_Array is array(Integer range <>) of Integer;
 
array : Int_Array := (1,2,3,4,5,6,7,8,9,10);
Line 149 ⟶ 298:
for I in array'range loop
Sum := Sum + array(I);
end loop;</langsyntaxhighlight>
Define the product function
<langsyntaxhighlight lang="ada">function Product(Item : Int_Array) return Integer is
Prod : Integer := 1;
begin
Line 158 ⟶ 307:
end loop;
return Prod;
end Product;</langsyntaxhighlight>
This function will raise the predefined exception Constraint_Error if the product overflows the values represented by type Integer
 
=={{header|Aime}}==
<langsyntaxhighlight lang="aime">void
compute(integer &s, integer &p, list l)
{
Line 185 ⟶ 334:
 
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>77
Line 191 ⟶ 340:
 
=={{header|ALGOL 68}}==
<langsyntaxhighlight lang="algol68">main:(
INT default upb := 3;
MODE INTARRAY = [default upb]INT;
Line 211 ⟶ 360:
) # int product # ;
printf(($" Sum: "g(0)$,sum,$", Product:"g(0)";"l$,int product(array)))
)</langsyntaxhighlight>
{{Out}}
<pre>
Line 218 ⟶ 367:
 
=={{header|ALGOL W}}==
<langsyntaxhighlight lang="algolw">begin
 
% computes the sum and product of intArray %
Line 251 ⟶ 400:
write( sum, product );
end
end.</langsyntaxhighlight>
 
{{out}}
Line 260 ⟶ 409:
=={{header|APL}}==
{{works with|APL2}}
<langsyntaxhighlight lang="apl"> sum ← +/ ⍝ sum (+) over (/) an array
prod ← ×/ ⍝ product (×) over (/) an array
lista ← 1 2 3 4 5 ⍝ assign a literal array to variable 'a'
sum lista ⍝ or simply: +/a
15
prod lista ⍝ or simply: ×/a
120</langsyntaxhighlight>
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}}==
<langsyntaxhighlight lang="applescript">set array to {1, 2, 3, 4, 5}
set sum to 0
set product to 1
Line 278 ⟶ 436:
set sum to sum + i
set product to product * i
end repeat</langsyntaxhighlight>
 
Condensed version of above, which also prints the results :
<syntaxhighlight lang="applescript">
<lang AppleScript>
set {array, sum, product} to {{1, 2, 3, 4, 5}, 0, 1}
repeat with i in array
Line 287 ⟶ 445:
end repeat
return sum & " , " & product as string
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 295 ⟶ 453:
Or, using an AppleScript implementation of '''fold'''/'''reduce''':
 
<langsyntaxhighlight AppleScriptlang="applescript">on summed(a, b)
a + b
end summed
Line 354 ⟶ 512:
end script
end if
end mReturn</langsyntaxhighlight>
{{Out}}
<langsyntaxhighlight AppleScriptlang="applescript">{{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, {sum:55}, {product:3628800}}</langsyntaxhighlight>
 
=={{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}}==
<langsyntaxhighlight lang="rebol">arr: 1..10
 
print ["Sum =" sum arr]
print ["Product =" product arr]</langsyntaxhighlight>
 
{{out}}
Line 368 ⟶ 675:
<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}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">numbers = 1,2,3,4,5
product := 1
loop, parse, numbers, `,
Line 377 ⟶ 698:
product *= A_LoopField
}
msgbox, sum = %sum%`nproduct = %product%</langsyntaxhighlight>
 
=={{header|AWK}}==
For array input, it is easiest to "deserialize" it from a string with the split() function.
<langsyntaxhighlight 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
55
Line 387 ⟶ 708:
$ 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</langsyntaxhighlight>
 
=={{header|Babel}}==
<langsyntaxhighlight lang="babel">main: { [2 3 5 7 11 13] sp }
 
sum! : { <- 0 -> { + } eachar }
Line 402 ⟶ 723:
Result:
41
30030</langsyntaxhighlight>
 
Perhaps better Babel:
 
<langsyntaxhighlight lang="babel">main:
{ [2 3 5 7 11 13]
ar2ls dup cp
Line 424 ⟶ 745:
{ * }
{ depth 1 > }
do_while } nest }</langsyntaxhighlight>
 
The nest operator creates a kind of argument-passing context -
Line 437 ⟶ 758:
=={{header|BASIC}}==
{{works with|FreeBASIC}}
<langsyntaxhighlight lang="freebasic">dim array(5) as integer = { 1, 2, 3, 4, 5 }
 
dim sum as integer = 0
Line 444 ⟶ 765:
sum += array(index)
prod *= array(index)
next</langsyntaxhighlight>
 
==={{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
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</langsyntaxhighlight>
 
==={{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:
 
<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}}===
<langsyntaxhighlight lang="freebasic">
'--- set some values into the array
DECLARE a[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10 } TYPE int
Line 474 ⟶ 809:
PRINT "The sum is ",sum
PRINT "The product is ",product
</langsyntaxhighlight>
 
==={{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}}===
<langsyntaxhighlight lang="bbcbasic"> DIM array%(5)
array%() = 1, 2, 3, 4, 5, 6
Line 486 ⟶ 840:
product% *= array%(I%)
NEXT
PRINT "Product of array elements = " ; product%</langsyntaxhighlight>
 
==={{header|IS-BASIC}}===
<langsyntaxhighlight ISlang="is-BASICbasic">100 RANDOMIZE
110 LET N=5
120 NUMERIC A(1 TO N)
Line 501 ⟶ 855:
200 LET SUM=SUM+A(I):LET PROD=PROD*A(I)
210 NEXT
220 PRINT "Sum =";SUM,"Product =";PROD</langsyntaxhighlight>
 
 
=={{header|BASIC256}}==
{{trans|Yabasic}}
<langsyntaxhighlight BASIC256lang="basic256">arraybase 1
dim array(5)
array[1] = 1
Line 522 ⟶ 876:
print "The sum is "; sum #15
print "and the product is "; prod #120
end</langsyntaxhighlight>
 
 
=={{header|bc}}==
<langsyntaxhighlight lang="bc">a[0] = 3.0
a[1] = 1
a[2] = 4.0
Line 539 ⟶ 893:
}
"Sum: "; s
"Product: "; p</langsyntaxhighlight>
 
=={{header|Befunge}}==
{{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.
<langsyntaxhighlight Befungelang="befunge">0 &>: #v_ $. @
>1- \ & + \v
^ <</langsyntaxhighlight>
 
=={{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}}==
<langsyntaxhighlight lang="bracmat">( ( sumprod
= sum prod num
. 0:?sum
Line 564 ⟶ 931:
)
& out$sumprod$(2 3 5 7 11 13 17 19)
);</langsyntaxhighlight>
{{Out}}
<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}}==
<langsyntaxhighlight lang="c">/* using pointer arithmetic (because we can, I guess) */
int arg[] = { 1,2,3,4,5 };
int arg_length = sizeof(arg)/sizeof(arg[0]);
Line 579 ⟶ 956:
sum += *p;
prod *= *p;
}</langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">int sum = 0, prod = 1;
int[] arg = { 1, 2, 3, 4, 5 };
foreach (int value in arg) {
sum += value;
prod *= value;
}</langsyntaxhighlight>
 
===Alternative using Linq (C# 3)===
{{works with|C sharp|C#|3}}
 
<langsyntaxhighlight lang="csharp">int[] arg = { 1, 2, 3, 4, 5 };
int sum = arg.Sum();
int prod = arg.Aggregate((runningProduct, nextFactor) => runningProduct * nextFactor);</langsyntaxhighlight>
 
=={{header|C++}}==
{{libheader|STL}}
<langsyntaxhighlight lang="cpp">#include <numeric>
#include <functional>
 
Line 606 ⟶ 983:
// 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>());</langsyntaxhighlight>
Template alternative:
<langsyntaxhighlight lang="cpp">// this would be more elegant using STL collections
template <typename T> T sum (const T *array, const unsigned n)
{
Line 635 ⟶ 1,012:
cout << sum(aflo,4) << " " << prod(aflo,4) << endl;
return 0;
}</langsyntaxhighlight>
 
=={{header|Chef}}==
 
<langsyntaxhighlight lang="chef">Sum and Product of Numbers as a Piece of Cake.
 
This recipe sums N given numbers.
Line 661 ⟶ 1,038:
Pour contents of 1st mixing bowl into the baking dish.
 
Serves 1.</langsyntaxhighlight>
 
=={{header|Clean}}==
<langsyntaxhighlight lang="clean">array = {1, 2, 3, 4, 5}
Sum = sum [x \\ x <-: array]
Prod = foldl (*) 1 [x \\ x <-: array]</langsyntaxhighlight>
 
=={{header|Clojure}}==
 
<langsyntaxhighlight lang="lisp">(defn sum [vals] (reduce + vals))
 
(defn product [vals] (reduce * vals))</langsyntaxhighlight>
 
=={{header|CLU}}==
<langsyntaxhighlight lang="clu">sum_and_product = proc (a: array[int]) returns (int,int) signals (overflow)
sum: int := 0
prod: int := 1
Line 692 ⟶ 1,069:
stream$putl(po, "Sum = " || int$unparse(sum))
stream$putl(po, "Product = " || int$unparse(prod))
end start_up</langsyntaxhighlight>
{{out}}
<pre>Sum = 55
Line 698 ⟶ 1,075:
 
=={{header|COBOL}}==
<langsyntaxhighlight lang="cobol"> IDENTIFICATION DIVISION.
PROGRAM-ID. array-sum-and-product.
 
Line 722 ⟶ 1,099:
 
GOBACK
.</langsyntaxhighlight>
 
=={{header|CoffeeScript}}==
<langsyntaxhighlight lang="coffeescript">
sum = (array) ->
array.reduce (x, y) -> x + y
Line 731 ⟶ 1,108:
product = (array) ->
array.reduce (x, y) -> x * y
</syntaxhighlight>
</lang>
 
=={{header|ColdFusion}}==
Sum of an Array,
<langsyntaxhighlight lang="cfm"><cfset Variables.myArray = [1,2,3,4,5,6,7,8,9,10]>
<cfoutput>#ArraySum(Variables.myArray)#</cfoutput></langsyntaxhighlight>
 
Product of an Array,
<langsyntaxhighlight lang="cfm"><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></langsyntaxhighlight>
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">(let ((data #(1 2 3 4 5))) ; the array
(values (reduce #'+ data) ; sum
(reduce #'* data))) ; product</langsyntaxhighlight>
 
The loop macro also has support for sums.
<langsyntaxhighlight lang="lisp">(loop for i in '(1 2 3 4 5) sum i)</langsyntaxhighlight>
 
=={{header|Crystal}}==
===Declarative===
<syntaxhighlight lang="ruby">
<lang Ruby>
def sum_product(a)
{ a.sum(), a.product() }
end
</syntaxhighlight>
</lang>
 
===Imperative===
<syntaxhighlight lang="ruby">
<lang Ruby>
def sum_product_imperative(a)
sum, product = 0, 1
Line 773 ⟶ 1,150:
{sum, product}
end
</syntaxhighlight>
</lang>
 
<syntaxhighlight lang="ruby">
<lang Ruby>
require "benchmark"
Benchmark.ips do |x|
Line 781 ⟶ 1,158:
x.report("imperative") { sum_product_imperative [1, 2, 3, 4, 5] }
end
</syntaxhighlight>
</lang>
 
<pre>declarative 8.1M (123.45ns) (± 2.99%) 65 B/op 1.30× slower
Line 787 ⟶ 1,164:
 
=={{header|D}}==
<langsyntaxhighlight lang="d">import std.stdio;
 
void main() {
Line 802 ⟶ 1,179:
writeln("Sum: ", sum);
writeln("Product: ", prod);
}</langsyntaxhighlight>
{{Out}}
<pre>Sum: 15
Product: 120</pre>
Compute sum and product of array in one pass (same output):
<langsyntaxhighlight lang="d">import std.stdio, std.algorithm, std.typecons;
 
void main() {
Line 817 ⟶ 1,194:
writeln("Sum: ", r[0]);
writeln("Product: ", r[1]);
}</langsyntaxhighlight>
 
=={{header|dc}}==
<langsyntaxhighlight lang="dc">1 3 5 7 9 11 13 0ss1sp[dls+sslp*spz0!=a]dsax[Sum: ]Plsp[Product: ]Plpp
Sum: 49
Product: 135135</langsyntaxhighlight>
 
=={{header|Delphi}}==
<langsyntaxhighlight lang="delphi">program SumAndProductOfArray;
 
{$APPTYPE CONSOLE}
Line 845 ⟶ 1,222:
Write('Product: ');
Writeln(lProduct);
end.</langsyntaxhighlight>
 
=={{header|E}}==
<langsyntaxhighlight lang="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 }</langsyntaxhighlight>
 
=={{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}}==
<langsyntaxhighlight lang="eiffel">
class
APPLICATION
Line 895 ⟶ 1,288:
 
end
</syntaxhighlight>
</lang>
{{Out}}
<pre>Sum of the elements of the array: 30
Line 902 ⟶ 1,295:
=={{header|Elena}}==
ELENA 5.0:
<langsyntaxhighlight lang="elena">import system'routines;
import extensions;
Line 911 ⟶ 1,304:
var sum := list.summarize(new Integer());
var product := list.accumulate(new Integer(1), (var,val => var * val));
}</langsyntaxhighlight>
 
=={{header|Elixir}}==
When an accumulator is omitted, the first element of the collection is used as the initial value of acc.
<langsyntaxhighlight 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)
Line 932 ⟶ 1,325:
iex(32)> Enum.reduce([], fn x,acc -> x*acc end)
** (Enum.EmptyError) empty error
(elixir) lib/enum.ex:1287: Enum.reduce/2</langsyntaxhighlight>
 
The function with sum
<langsyntaxhighlight lang="elixir">Enum.sum([1,2,3,4,5]) #=> 15</langsyntaxhighlight>
 
=={{header|Emacs Lisp}}==
{{works with|XEmacs|version 21.5.21}}
 
<langsyntaxhighlight lang="lisp">(setqlet ((array [1 2 3 4 5]))
(eval (concatenateapply #'list+ '(+)append array nil))
(eval (concatenateapply #'list* '(*)append array nil)))</langsyntaxhighlight>
 
{{libheader|cl-lib}}
===With a list===
 
<syntaxhighlight lang ="lisp">(setq arrayrequire '(1 2 3 4 5)cl-lib)
(apply '+ array)
(apply '* array)</lang>
 
(let ((array [1 2 3 4 5]))
===With explicit conversion===
(cl-reduce #'+ array)
(cl-reduce #'* array))</syntaxhighlight>
 
{{libheader|seq.el}}
<lang lisp>(setq array [1 2 3 4 5])
 
(apply '+ (append array nil))
<syntaxhighlight lang="lisp">(require 'seq)
(apply '* (append array nil))</lang>
 
(let ((array [1 2 3 4 5]))
(seq-reduce #'+ array 0)
(seq-reduce #'* array 1))</syntaxhighlight>
 
=={{header|Erlang}}==
Using the standard libraries:
<langsyntaxhighlight lang="erlang">% 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).</langsyntaxhighlight>
To compute sum and products in one pass:
<langsyntaxhighlight lang="erlang">
{Prod,Sum} = lists:foldl(fun (X, {P,S}) -> {P*X,S+X} end, {1,0}, lists:seq(1,10)).</langsyntaxhighlight>
Or defining our own versions:
<langsyntaxhighlight lang="erlang">-module(list_sum).
-export([sum_rec/1, sum_tail/1]).
 
Line 983 ⟶ 1,379:
Acc;
sum_tail([Head|Tail], Acc) ->
sum_tail(Tail, Head + Acc).</langsyntaxhighlight>
 
=={{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
&lt;- ` '''formal''' array;
'''begin'''
'''new''' sum; '''new''' product; '''new''' i; '''new''' v; '''label''' arrayLoop;
v &lt;- array;
sum &lt;- 0;
product &lt;- 1;
i &lt;- 0;
arrayLoop: '''if''' [ i &lt;- i + 1 ] &lt;= '''length''' array '''then''' '''begin'''
sum &lt;- sum + v[ i ];
product &lt;- product * v[ i ];
'''goto''' arrayLoop
'''end''' '''else''' 0;
sumField &lt;- 1;
productField &lt;- 2;
( sum, product )
'''end'''
&apos;;
'''begin'''
'''new''' sp;
sp &lt;- sumAndProduct( ( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ) );
'''out''' sp[ sumField ];
'''out''' sp[ productField ]
'''end'''
'''end''' $
 
=={{header|Euphoria}}==
<langsyntaxhighlight lang="euphoria">sequence array
integer sum,prod
 
Line 999 ⟶ 1,426:
 
printf(1,"sum is %d\n",sum)
printf(1,"prod is %d\n",prod)</langsyntaxhighlight>
 
{{Out}}
Line 1,008 ⟶ 1,435:
 
=={{header|F_Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">
let numbers = [| 1..10 |]
let sum = numbers |> Array.sum
let product = numbers |> Array.reduce (*)
</syntaxhighlight>
</lang>
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">1 5 1 <range> [ sum . ] [ product . ] bi
15 120
{ 1 2 3 4 } [ sum ] [ product ] bi
10 24</langsyntaxhighlight>
sum and product are defined in the sequences vocabulary:
<langsyntaxhighlight lang="factor">: sum ( seq -- n ) 0 [ + ] reduce ;
: product ( seq -- n ) 1 [ * ] reduce ;</langsyntaxhighlight>
 
=={{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.
<langsyntaxhighlight lang="false">1 2 3 4 5 {input "array"}
5 {length of input}
0s: {sum}
Line 1,033 ⟶ 1,460:
 
"Sum: "s;."
Product: "p;.</langsyntaxhighlight>
{{out}}
<pre>Sum: 15
Line 1,040 ⟶ 1,467:
=={{header|Fantom}}==
 
<langsyntaxhighlight lang="fantom">
class Main
{
Line 1,073 ⟶ 1,500:
}
}
</syntaxhighlight>
</lang>
 
=={{header|Fermat}}==
<langsyntaxhighlight lang="fermat">
[a]:=[(1,1,2,3,5,8,13)];
!!Sigma<i=1,7>[a[i]];
!!Prod<i=1,7>[a[i]];
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,088 ⟶ 1,515:
 
=={{header|Forth}}==
<langsyntaxhighlight lang="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 ;
Line 1,095 ⟶ 1,522:
 
' + 0 a 5 reduce . \ 15
' * 1 a 5 reduce . \ 120</langsyntaxhighlight>
 
=={{header|Fortran}}==
In ISO Fortran 90 and later, use SUM and PRODUCT intrinsics:
<langsyntaxhighlight lang="fortran">integer, dimension(10) :: a = (/ (i, i=1, 10) /)
integer :: sresult, presult
 
sresult = sum(a)
presult = product(a)</langsyntaxhighlight>
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Dim a(1 To 4) As Integer = {1, 4, 6, 3}
Line 1,118 ⟶ 1,545:
Print
Print "Press any key to quit"
Sleep</langsyntaxhighlight>
 
{{out}}
Line 1,124 ⟶ 1,551:
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}}==
<langsyntaxhighlight lang="frink">
a = [1,2,3,5,7]
sum[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}}
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 &mdash;i.e. XML, JSON&mdash; they are intended for storage and transfer purposes more than visualization and edition.
 
Programs in Fōrmulæ are created/edited online in its [https://formulae.org website], However they run on execution servers. By default remote servers are used, but they are limited in memory and processing power, since they are intended for demonstration and casual use. A local server can be downloaded and installed, it has no limitations (it runs in your own computer). Because of that, example programs can be fully visualized and edited, but some of them will not run if they require a moderate or heavy computation/memory resources, and no local server is being used.
 
'''Solution'''
In '''[https://formulae.org/?example=Sum_and_product_of_an_array this]''' page you can see the program(s) related to this task and their results.
 
[[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]'''
<langsyntaxhighlight lang="gambas">Public Sub Main()
Dim iList As Integer[] = [1, 2, 3, 4, 5]
Dim iSum, iCount As Integer
Line 1,156 ⟶ 1,673:
Print "The Product =\t" & iPrd
 
End</langsyntaxhighlight>
Output:
<pre>
Line 1,162 ⟶ 1,679:
The Product = 120
</pre>
 
 
=={{header|GAP}}==
<langsyntaxhighlight lang="gap">v := [1 .. 8];
 
Sum(v);
Line 1,178 ⟶ 1,696:
 
Product(v, n -> 1/n);
# 1/40320</langsyntaxhighlight>
 
 
 
=={{header|GFA Basic}}==
 
<langsyntaxhighlight lang="basic">
DIM a%(10)
' put some values into the array
Line 1,198 ⟶ 1,718:
PRINT "Sum is ";sum%
PRINT "Product is ";product%
</syntaxhighlight>
</lang>
 
 
 
=={{header|Go}}==
;Implementation
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 1,213 ⟶ 1,735:
}
fmt.Println(sum, prod)
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,219 ⟶ 1,741:
</pre>
;Library
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,232 ⟶ 1,754:
fmt.Println("Sum: ", floats.Sum(a))
fmt.Println("Product:", floats.Prod(a))
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,241 ⟶ 1,763:
=={{header|Groovy}}==
Groovy adds a "sum()" method for collections, but not a "product()" method:
<langsyntaxhighlight lang="groovy">[1,2,3,4,5].sum()</langsyntaxhighlight>
However, for general purpose "reduction" or "folding" operations, Groovy does provide an "inject()" method for collections similar to "inject" in Ruby.
<langsyntaxhighlight lang="groovy">[1,2,3,4,5].inject(0) { sum, val -> sum + val }
[1,2,3,4,5].inject(1) { prod, val -> prod * val }</langsyntaxhighlight>
You can also combine these operations:
<langsyntaxhighlight lang="groovy">println ([1,2,3,4,5].inject([sum: 0, product: 1]) { result, value ->
[sum: result.sum + value, product: result.product * value]})</langsyntaxhighlight>
 
=={{header|GW-BASIC}}==
{{works with|Applesoft BASIC}}
{{works with|BASICA}}
{{works with|Chipmunk Basic|3.6.4}}
{{works with|GW-BASIC}}
{{works with|QBasic}}
{{works with|MSX BASIC}}
 
<langsyntaxhighlight lang="qbasic">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
Line 1,265 ⟶ 1,791:
77 NEXT I
80 PRINT "The sum is "; S;
90 PRINT " and the product is "; P</langsyntaxhighlight>
 
=={{header|Haskell}}==
For lists, ''sum'' and ''product'' are already defined in the Prelude:
<langsyntaxhighlight lang="haskell">values = [1..10]
 
s = sum values -- the easy way
Line 1,275 ⟶ 1,801:
 
s1 = foldl (+) 0 values -- the hard way
p1 = foldl (*) 1 values</langsyntaxhighlight>
To do the same for an array, just convert it lazily to a list:
<langsyntaxhighlight lang="haskell">import Data.Array
 
values = listArray (1,10) [1..10]
 
s = sum . elems $ values
p = product . elems $ values</langsyntaxhighlight>
 
Or perhaps:
<langsyntaxhighlight lang="haskell">import Data.Array (listArray, elems)
 
main :: IO ()
main = mapM_ print $ [sum, product] <*> [elems $ listArray (1, 10) [11 .. 20]]</langsyntaxhighlight>
{{Out}}
<pre>155
Line 1,294 ⟶ 1,820:
 
=={{header|HicEst}}==
<langsyntaxhighlight lang="hicest">array = $ ! 1, 2, ..., LEN(array)
 
sum = SUM(array)
Line 1,303 ⟶ 1,829:
ENDDO
 
WRITE(ClipBoard, Name) n, sum, product ! n=100; sum=5050; product=9.33262154E157;</langsyntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
The program below prints the sum and product of the arguments to the program.
<langsyntaxhighlight Iconlang="icon">procedure main(arglist)
every ( sum := 0 ) +:= !arglist
every ( prod := 1 ) *:= !arglist
write("sum := ", sum,", prod := ",prod)
end</langsyntaxhighlight>
 
=={{header|IDL}}==
<langsyntaxhighlight lang="idl">array = [3,6,8]
print,total(array)
print,product(array)</langsyntaxhighlight>
 
=={{header|Inform 7}}==
<langsyntaxhighlight lang="inform7">Sum And Product is a room.
 
To decide which number is the sum of (N - number) and (M - number) (this is summing):
Line 1,330 ⟶ 1,856:
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.</langsyntaxhighlight>
 
=={{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:
 
<langsyntaxhighlight lang="j"> sum 1 3 5 7 9 11 13
49
product 1 3 5 7 9 11 13
Line 1,360 ⟶ 1,893:
466 472 462
product"1 a
5.53041e15 9.67411e15 1.93356e15</langsyntaxhighlight>
 
=={{header|Java}}==
{{works with|Java|1.5+}}
<langsyntaxhighlight lang="java5">public class SumProd
{
public static void main(final String[] args)
Line 1,377 ⟶ 1,910:
}
}
}</langsyntaxhighlight>
 
{{works with|Java|1.8+}}
<langsyntaxhighlight lang="java5">import java.util.Arrays;
 
public class SumProd
Line 1,391 ⟶ 1,924:
System.out.printf("product = %d\n", Arrays.stream(arg).reduce(1, (a, b) -> a * b));
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,401 ⟶ 1,934:
=={{header|JavaScript}}==
===ES5===
<langsyntaxhighlight lang="javascript">var array = [1, 2, 3, 4, 5],
sum = 0,
prod = 1,
Line 1,409 ⟶ 1,942:
prod *= array[i];
}
alert(sum + ' ' + prod);</langsyntaxhighlight>
 
 
{{Works with|Javascript|1.8}}
Where supported, the reduce method can also be used:
<langsyntaxhighlight lang="javascript">var array = [1, 2, 3, 4, 5],
sum = array.reduce(function (a, b) {
return a + b;
Line 1,421 ⟶ 1,954:
return a * b;
}, 1);
alert(sum + ' ' + prod);</langsyntaxhighlight>
 
===ES6===
<langsyntaxhighlight JavaScriptlang="javascript">(() => {
'use strict';
 
Line 1,442 ⟶ 1,975:
.map(f => f([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]))
);
})();</langsyntaxhighlight>
 
{{Out}}
Line 1,449 ⟶ 1,982:
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:
<langsyntaxhighlight lang="jq">[4,6,8] | add
# => 18</langsyntaxhighlight>
<langsyntaxhighlight lang="jq">[range(2;5) * 2] | add
# => 18</langsyntaxhighlight>
An efficient companion filter for computing the product of the items in an array can be defined as follows:
<langsyntaxhighlight lang="jq">def prod: reduce .[] as $i (1; . * $i);</langsyntaxhighlight>
Examples:
<langsyntaxhighlight lang="jq">[4,6,8] | prod
# => 192</langsyntaxhighlight>
10!
<langsyntaxhighlight lang="jq">[range(1;11)] | prod
# =>3628800</langsyntaxhighlight>
 
=={{header|Julia}}==
<langsyntaxhighlight lang="julia">julia> sum([4,6,8])
18
 
Line 1,476 ⟶ 2,013:
 
julia> prod([4,6,8])
192</langsyntaxhighlight>
 
=={{header|K}}==
<langsyntaxhighlight lang="k"> sum: {+/}x
product: {*/}x
a: 1 3 5 7 9 11 13
Line 1,485 ⟶ 2,022:
49
product a
135135</langsyntaxhighlight>
 
It is easy to see the relationship of K to J here.
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.1.2
 
fun main(args: Array<String>) {
Line 1,499 ⟶ 2,036:
val product = a.fold(1) { acc, i -> acc * i }
println("Product is $product")
}</langsyntaxhighlight>
 
{{out}}
Line 1,510 ⟶ 2,047:
=={{header|Lambdatalk}}==
 
<langsyntaxhighlight 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
Line 1,526 ⟶ 2,063:
9332621544394415268169923885626670049071596826438162146859296389521759999322991
5608941463976156518286253697920827223758251185210916864000000000000000000000000
</syntaxhighlight>
</lang>
 
=={{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}}==
<langsyntaxhighlight lang="lang5">4 iota 1 + dup
 
'+ reduce
'* reduce</langsyntaxhighlight>
 
=={{header|langur}}==
<langsyntaxhighlight lang="langur">val .arrlist = series 19
writeln " array list: ", .arrlist
writeln " sum: ", fold f .x fn{+ .y}, .arrlist
writeln "product: ", fold f .x x .yfn{*}, .arr</lang>list
</syntaxhighlight>
 
{{works with|langur|0.6.6}}
<lang langur>val .arr = series 19
writeln " array: ", .arr
writeln " sum: ", fold f{+}, .arr
writeln "product: ", fold f{x}, .arr</lang>
 
{{out}}
<pre> array 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}}==
<langsyntaxhighlight Lassolang="lasso">local(x = array(1,2,3,4,5,6,7,8,9,10))
// sum of array elements
'Sum: '
Line 1,562 ⟶ 2,105:
local(product = 1)
with n in #x do => { #product *= #n }
#product</langsyntaxhighlight>
{{out}}
<pre>Sum: 55
Line 1,568 ⟶ 2,111:
 
=={{header|Liberty BASIC}}==
<langsyntaxhighlight lang="lb">Dim array(19)
 
For i = 0 To 19
Line 1,582 ⟶ 2,125:
 
Print "Sum is " + str$(sum)
Print "Product is " + str$(product)</langsyntaxhighlight>
 
=={{header|Lingo}}==
<langsyntaxhighlight lang="lingo">on sum (intList)
res = 0
repeat with v in intList
Line 1,599 ⟶ 2,142:
end repeat
return res
end</langsyntaxhighlight>
 
=={{header|LiveCode}}==
<langsyntaxhighlight LiveCodelang="livecode">//sum
put "1,2,3,4" into nums
split nums using comma
Line 1,616 ⟶ 2,159:
end if
end repeat
answer prodnums</langsyntaxhighlight>
 
=={{header|Logo}}==
<langsyntaxhighlight lang="logo">print apply "sum arraytolist {1 2 3 4 5}
print apply "product arraytolist {1 2 3 4 5}</langsyntaxhighlight>
 
=={{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}}==
<langsyntaxhighlight lang="lua">
function sumf(a, ...) return a and a + sumf(...) or 0 end
function sumt(t) return sumf(unpack(t)) end
Line 1,630 ⟶ 2,206:
 
print(sumt{1, 2, 3, 4, 5})
print(prodt{1, 2, 3, 4, 5})</langsyntaxhighlight>
 
<langsyntaxhighlight lang="lua">
function table.sum(arr, length)
--same as if <> then <> else <>
Line 1,645 ⟶ 2,221:
print(table.sum(t,#t))
print(table.product(t,3))
</syntaxhighlight>
</lang>
 
=={{header|Lucid}}==
prints a running sum and product of sequence 1,2,3...
<langsyntaxhighlight lang="lucid">[%sum,product%]
where
x = 1 fby x + 1;
sum = 0 fby sum + x;
product = 1 fby product * x
end</langsyntaxhighlight>
 
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module Checkit {
a = (1,2,3,4,5,6,7,8,9,10)
Line 1,668 ⟶ 2,244:
}
checkit
</syntaxhighlight>
</lang>
 
=={{header|Maple}}==
<langsyntaxhighlight lang="maple">a := Array([1, 2, 3, 4, 5, 6]);
add(a);
mul(a);</langsyntaxhighlight>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
Mathematica provides many ways of doing the sum of an array (any kind of numbers or symbols):
<langsyntaxhighlight Mathematicalang="mathematica">a = {1, 2, 3, 4, 5}
Plus @@ a
Apply[Plus, a]
Line 1,684 ⟶ 2,260:
a // Total
Sum[a[[i]], {i, 1, Length[a]}]
Sum[i, {i, a}]</langsyntaxhighlight>
all give 15. For product we also have a couple of choices:
<langsyntaxhighlight Mathematicalang="mathematica">a = {1, 2, 3, 4, 5}
Times @@ a
Apply[Times, a]
Product[a[[i]], {i, 1, Length[a]}]
Product[i, {i, a}]</langsyntaxhighlight>
all give 120.
 
Line 1,697 ⟶ 2,273:
 
Sample Usage:
<langsyntaxhighlight MATLABlang="matlab">>> array = [1 2 3;4 5 6;7 8 9]
 
array =
Line 1,731 ⟶ 2,307:
6
120
504</langsyntaxhighlight>
 
=={{header|Maxima}}==
 
<langsyntaxhighlight lang="maxima">lreduce("+", [1, 2, 3, 4, 5, 6, 7, 8]);
36
 
lreduce("*", [1, 2, 3, 4, 5, 6, 7, 8]);
40320</langsyntaxhighlight>
 
=={{header|MAXScript}}==
<langsyntaxhighlight lang="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</langsyntaxhighlight>
 
=={{header|min}}==
{{works with|min|0.19.3}}
<langsyntaxhighlight lang="min">(1 2 3 4 5) ((sum) (1 '* reduce)) cleave
"Sum: $1\nProduct: $2" get-stack % puts</langsyntaxhighlight>
{{out}}
<pre>
Line 1,759 ⟶ 2,335:
 
=={{header|МК-61/52}}==
<syntaxhighlight lang="text">^ 1 ПE + П0 КИП0 x#0 18 ^ ИПD
+ ПD <-> ИПE * ПE БП 05 С/П</langsyntaxhighlight>
 
''Instruction'': РX - array length, Р1:РC - array, РD and РE - sum and product of an array.
 
=={{header|Modula-3}}==
<langsyntaxhighlight lang="modula3">MODULE Sumprod EXPORTS Main;
 
FROM IO IMPORT Put;
Line 1,781 ⟶ 2,357:
Put("Sum of array: " & Int(sum) & "\n");
Put("Product of array: " & Int(prod) & "\n");
END Sumprod.</langsyntaxhighlight>
{{Out}}
<pre>Sum of array: 15
Line 1,787 ⟶ 2,363:
 
=={{header|MUMPS}}==
<syntaxhighlight lang="mumps">
<lang MUMPS>
SUMPROD(A)
;Compute the sum and product of the numbers in the array A
Line 1,799 ⟶ 2,375:
WRITE !,"The product of the array is "_PROD
KILL SUM,PROD,POS
QUIT</langsyntaxhighlight>
Example: <pre>
USER>SET C(-1)=2,C("A")=3,C(42)=1,C(0)=7
Line 1,820 ⟶ 2,396:
=={{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.
<langsyntaxhighlight Nemerlelang="nemerle">using System;
using System.Console;
using System.Collections.Generic;
Line 1,849 ⟶ 2,425:
WriteLine("Sum is: {0}\tProduct is: {1}", suml, proda);
}
}</langsyntaxhighlight>
 
=={{header|NetRexx}}==
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
 
options replace format comments java crossref savelog symbols binary
Line 1,876 ⟶ 2,452:
 
return
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 1,885 ⟶ 2,461:
 
=={{header|NewLISP}}==
<langsyntaxhighlight NewLISPlang="newlisp">(setq a '(1 2 3 4 5))
(apply + a)
(apply * a)</langsyntaxhighlight>
 
=={{header|Nial}}==
Nial being an array language, what applies to individual elements are extended to cover array operations by default strand notation
<langsyntaxhighlight lang="nial">+ 1 2 3
= 6
* 1 2 3
= 6</langsyntaxhighlight>
array notation
<syntaxhighlight lang ="nial">+ [1,2,3]</langsyntaxhighlight>
grouped notation
<langsyntaxhighlight lang="nial">(* 1 2 3)
= 6
* (1 2 3)
= 6</langsyntaxhighlight>
(All these notations are equivalent)
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">var xs = [1, 2, 3, 4, 5, 6]
 
var sum, product: int
Line 1,913 ⟶ 2,489:
for x in xs:
sum += x
product *= x</langsyntaxhighlight>
 
Or functionally:
<langsyntaxhighlight lang="nim">import sequtils
 
let
xs = [1, 2, 3, 4, 5, 6]
sum = xs.foldl(a + b)
product = xs.foldl(a * b)</langsyntaxhighlight>
 
Or using a math function:
<langsyntaxhighlight lang="nim">import math
 
let numbers = [1, 5, 4]
Line 1,931 ⟶ 2,507:
var product = 1
for n in numbers:
product *= n</langsyntaxhighlight>
 
=={{header|Objeck}}==
<langsyntaxhighlight lang="objeck">
sum := 0;
prod := 1;
Line 1,942 ⟶ 2,518:
prod *= arg[i];
};
</syntaxhighlight>
</lang>
 
=={{header|Objective-C}}==
{{works with|GCC|4.0.1 (apple)}}
Sum:
<langsyntaxhighlight lang="objc">- (float) sum:(NSMutableArray *)array
{
int i, sum, value;
Line 1,959 ⟶ 2,535:
return suml;
}</langsyntaxhighlight>
Product:
<langsyntaxhighlight lang="objc">- (float) prod:(NSMutableArray *)array
{
int i, prod, value;
Line 1,973 ⟶ 2,549:
return suml;
}</langsyntaxhighlight>
 
=={{header|OCaml}}==
===Arrays===
<langsyntaxhighlight lang="ocaml">(* ints *)
let a = [| 1; 2; 3; 4; 5 |];;
Array.fold_left (+) 0 a;;
Line 1,984 ⟶ 2,560:
let a = [| 1.0; 2.0; 3.0; 4.0; 5.0 |];;
Array.fold_left (+.) 0.0 a;;
Array.fold_left ( *.) 1.0 a;;</langsyntaxhighlight>
===Lists===
<langsyntaxhighlight lang="ocaml">(* ints *)
let x = [1; 2; 3; 4; 5];;
List.fold_left (+) 0 x;;
Line 1,993 ⟶ 2,569:
let x = [1.0; 2.0; 3.0; 4.0; 5.0];;
List.fold_left (+.) 0.0 x;;
List.fold_left ( *.) 1.0 x;;</langsyntaxhighlight>
 
=={{header|Octave}}==
<langsyntaxhighlight lang="octave">a = [ 1, 2, 3, 4, 5, 6 ];
b = [ 10, 20, 30, 40, 50, 60 ];
vsum = a + b;
vprod = a .* b;</langsyntaxhighlight>
 
=={{header|Oforth}}==
 
<langsyntaxhighlight Oforthlang="oforth">[1, 2, 3, 4, 5 ] sum println
[1, 3, 5, 7, 9 ] prod println</langsyntaxhighlight>
 
{{out}}
Line 2,013 ⟶ 2,589:
 
=={{header|Ol}}==
<langsyntaxhighlight lang="scheme">
(print (fold + 0 '(1 2 3 4 5)))
(print (fold * 1 '(1 2 3 4 5)))
</syntaxhighlight>
</lang>
 
=={{header|ooRexx}}==
{{trans|REXX}}
<langsyntaxhighlight lang="oorexx">a=.my_array~new(20)
do i=1 To 20
a[i]=i
Line 2,041 ⟶ 2,617:
prod*=self[i]
End
Return prod</langsyntaxhighlight>
{{out}}
<pre>1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20
Line 2,049 ⟶ 2,625:
=={{header|Oz}}==
Calculations like this are typically done on lists, not on arrays:
<langsyntaxhighlight lang="oz">declare
Xs = [1 2 3 4 5]
Sum = {FoldL Xs Number.'+' 0}
Line 2,055 ⟶ 2,631:
in
{Show Sum}
{Show Product}</langsyntaxhighlight>
 
If you are actually working with arrays, a more imperative approach seems natural:
<langsyntaxhighlight lang="oz">declare
Arr = {Array.new 1 3 0}
Sum = {NewCell 0}
Line 2,069 ⟶ 2,645:
Sum := @Sum + Arr.I
end
{Show @Sum}</langsyntaxhighlight>
 
=={{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:
<langsyntaxhighlight lang="parigp">vecsum1(v)={
sum(i=1,#v,v[i])
};
vecprod(v)={
prod(i=1,#v,v[i])
};</langsyntaxhighlight>
 
{{works with|PARI/GP|2.10.0+}}
Line 2,087 ⟶ 2,663:
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">my @list = ( 1, 2, 3 );
 
my ( $sum, $prod ) = ( 0, 1 );
$sum += $_ foreach @list;
$prod *= $_ foreach @list;</langsyntaxhighlight>
Or using the [https://metacpan.org/pod/List::Util List::Util] module:
<langsyntaxhighlight lang="perl">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);</langsyntaxhighlight>
{{out}}
<pre>Sum: 45
Line 2,104 ⟶ 2,680:
=={{header|Phix}}==
{{libheader|Phix/basics}}
<!--<langsyntaxhighlight Phixlang="phix">-->
<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>
<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>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 2,116 ⟶ 2,692:
 
=={{header|Phixmonti}}==
<langsyntaxhighlight Phixmontilang="phixmonti">include ..\Utilitys.pmt
 
( 1 2 3 4 5 )
Line 2,128 ⟶ 2,704:
drop
 
"mult is " print print nl</langsyntaxhighlight>
 
=={{header|PHP}}==
<langsyntaxhighlight lang="php">$array = array(1,2,3,4,5,6,7,8,9);
echo array_sum($array);
echo array_product($array);</langsyntaxhighlight>
 
=={{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}}==
<langsyntaxhighlight PicoLisplang="picolisp">(let Data (1 2 3 4 5)
(cons
(apply + Data)
(apply * Data) ) )</langsyntaxhighlight>
{{Out}}
<pre>(15 . 120)</pre>
 
=={{header|PL/I}}==
<langsyntaxhighlight lang="pli">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));</langsyntaxhighlight>
 
=={{header|Plain English}}==
<langsyntaxhighlight lang="plainenglish">An element is a thing with a number.
 
To find a sum and a product of some elements:
Line 2,183 ⟶ 2,809:
Shut down.
 
A sum is a number.</langsyntaxhighlight>
{{out}}
<pre>
Line 2,192 ⟶ 2,818:
=={{header|Pop11}}==
Simple loop:
<langsyntaxhighlight 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
ar(i) + sum -> sum;
ar(i) * prod -> prod;
endfor;</langsyntaxhighlight>
One can alternatively use second order iterator:
<langsyntaxhighlight 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 * prod -> prod; endprocedure);</langsyntaxhighlight>
 
=={{header|PostScript}}==
<syntaxhighlight lang="text">
/sumandproduct
{
Line 2,224 ⟶ 2,850:
prod ==
}def
</syntaxhighlight>
</lang>
 
{{libheader|initlib}}
<langsyntaxhighlight lang="postscript">
% sum
[1 1 1 1 1] 0 {add} fold
Line 2,233 ⟶ 2,859:
[1 1 1 1 1] 1 {mul} fold
 
</syntaxhighlight>
</lang>
 
=={{header|PowerShell}}==
The <code>Measure-Object</code> cmdlet already knows how to compute a sum:
<langsyntaxhighlight lang="powershell">function Get-Sum ($a) {
return ($a | Measure-Object -Sum).Sum
}</langsyntaxhighlight>
But not how to compute a product:
<langsyntaxhighlight lang="powershell">function Get-Product ($a) {
if ($a.Length -eq 0) {
return 0
Line 2,251 ⟶ 2,877:
return $p
}
}</langsyntaxhighlight>
One could also let PowerShell do all the work by simply creating an expression to evaluate:
 
{{works with|PowerShell|2}}
<langsyntaxhighlight lang="powershell">function Get-Product ($a) {
if ($a.Length -eq 0) {
return 0
Line 2,261 ⟶ 2,887:
$s = $a -join '*'
return (Invoke-Expression $s)
}</langsyntaxhighlight>
Even nicer, however, is a function which computes both at once and returns a custom object with appropriate properties:
<langsyntaxhighlight lang="powershell">function Get-SumAndProduct ($a) {
$sum = 0
if ($a.Length -eq 0) {
Line 2,278 ⟶ 2,904:
$ret | Add-Member NoteProperty Product $prod
return $ret
}</langsyntaxhighlight>
{{Out}}
<pre>PS> Get-SumAndProduct 5,9,7,2,3,8,4
Line 2,287 ⟶ 2,913:
 
=={{header|Prolog}}==
<langsyntaxhighlight lang="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.</langsyntaxhighlight>
 
test
Line 2,300 ⟶ 2,926:
 
Using fold
<langsyntaxhighlight lang="prolog">
add(A,B,R):-
R is A + B.
Line 2,324 ⟶ 2,950:
Prod = 24 .
 
</syntaxhighlight>
</lang>
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">Dim MyArray(9)
Define a, sum=0, prod=1
 
Line 2,340 ⟶ 2,966:
 
Debug "The sum is " + Str(sum) ; Present the results
Debug "Product is " + Str(prod)</langsyntaxhighlight>
 
=={{header|Python}}==
{{works with|Python|2.5}}
<langsyntaxhighlight lang="python">numbers = [1, 2, 3]
total = sum(numbers)
 
product = 1
for i in numbers:
product *= i</langsyntaxhighlight>
Or functionally (faster but perhaps less clear):
{{works with|Python|2.5}}
<langsyntaxhighlight lang="python">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)</langsyntaxhighlight>
{{libheader|NumPy}}
<langsyntaxhighlight lang="python">from numpy import r_
numbers = r_[1:4]
total = numbers.sum()
product = numbers.prod()</langsyntaxhighlight>
 
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}}
<langsyntaxhighlight lang="python">import math
total = math.fsum(floats)</langsyntaxhighlight>
 
 
Line 2,373 ⟶ 2,999:
{{works with|QuickBasic}}
{{works with|True BASIC}}
<langsyntaxhighlight QBasiclang="qbasic">DIM array(1 TO 5)
DATA 1, 2, 3, 4, 5
FOR index = LBOUND(array) TO UBOUND(array)
Line 2,387 ⟶ 3,013:
PRINT "The sum is "; sum
PRINT "and the product is "; prod
END</langsyntaxhighlight>
 
 
=={{header|Quackery}}==
<langsyntaxhighlight Quackerylang="quackery">[ 0 swap witheach + ] is sum ( [ --> n )
 
[ 1 swap witheach * ] is product ( [ --> n )</langsyntaxhighlight>
In the shell (i.e. Quackery REPL):
<syntaxhighlight lang="quackery">
<lang Quackery>
/O> ' [ 1 2 3 4 5 ] sum echo cr
... ' [ 1 2 3 4 5 ] product echo
Line 2,401 ⟶ 3,027:
15
120
Stack empty.</langsyntaxhighlight>
=={{header|R}}==
<langsyntaxhighlight lang="r">total <- sum(1:5)
product <- prod(1:5)</langsyntaxhighlight>
 
=={{header|Racket}}==
 
<langsyntaxhighlight lang="racket">#lang racket
 
(for/sum ([x #(3 1 4 1 5 9)]) x)
(for/product ([x #(3 1 4 1 5 9)]) x)</langsyntaxhighlight>
 
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku" perl6line>my @ary = 1, 5, 10, 100;
say 'Sum: ', [+] @ary;
say 'Product: ', [*] @ary;</langsyntaxhighlight>
 
=={{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}}==
<langsyntaxhighlight lang="raven">0 [ 1 2 3 ] each +
1 [ 1 2 3 ] each *</langsyntaxhighlight>
 
=={{header|REBOL}}==
<langsyntaxhighlight REBOLlang="rebol">REBOL [
Title: "Sum and Product"
URL: http://rosettacode.org/wiki/Sum_and_product_of_array
Line 2,458 ⟶ 3,101:
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]]</langsyntaxhighlight>
 
{{Out}}
Line 2,470 ⟶ 3,113:
 
=={{header|Red}}==
<langsyntaxhighlight lang="rebol">Red [
red-version: 0.6.4
description: "Find the sum and product of an array of numbers."
Line 2,487 ⟶ 3,130:
print a
print ["Sum:" sum a]
print ["Product:" product a]</langsyntaxhighlight>
{{out}}
<pre>
Line 2,496 ⟶ 3,139:
 
=={{header|REXX}}==
<langsyntaxhighlight lang="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.*/
Line 2,512 ⟶ 3,155:
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. */</langsyntaxhighlight>
'''output''' using the default input of: &nbsp; <tt> 20 </tt>
<pre>
Line 2,520 ⟶ 3,163:
 
=={{header|Ring}}==
<langsyntaxhighlight 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>
</lang>
 
=={{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>
 
=={{header|Ruby}}==
<langsyntaxhighlight 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 }
# => 15
p product = arr.inject(1) { |prod, element| prod * element }
# => 120</langsyntaxhighlight>
 
{{works with|Ruby|1.8.7}}
<langsyntaxhighlight lang="ruby">arr = [1,2,3,4,5]
p sum = arr.inject(0, :+) #=> 15
p product = arr.inject(1, :*) #=> 120
Line 2,542 ⟶ 3,200:
# then the first element of collection is used as the initial value of memo.
p sum = arr.inject(:+) #=> 15
p product = arr.inject(:*) #=> 120</langsyntaxhighlight>
 
Note: When the Array is empty, the initial value returns. However, nil returns if not giving an initial value.
<langsyntaxhighlight lang="ruby">arr = []
p arr.inject(0, :+) #=> 0
p arr.inject(1, :*) #=> 1
p arr.inject(:+) #=> nil
p arr.inject(:*) #=> nil</langsyntaxhighlight>
 
Enumerable#reduce is the alias of Enumerable#inject.
 
{{works with|Ruby|1.9.3}}
<langsyntaxhighlight lang="ruby">arr = [1,2,3,4,5]
p sum = arr.sum #=> 15
p [].sum #=> 0</langsyntaxhighlight>
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang="runbasic">dim array(100)
for i = 1 To 100
array(i) = rnd(0) * 100
Line 2,571 ⟶ 3,229:
Print " Sum is ";sum
Print "Product is ";product</langsyntaxhighlight>
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">
 
fn main() {
Line 2,589 ⟶ 3,247:
println!("the sum is {} and the product is {}", sum, product);
}
</syntaxhighlight>
</lang>
 
=={{header|S-lang}}==
<langsyntaxhighlight Slang="s-lang">variable a = [5, -2, 3, 4, 666, 7];</langsyntaxhighlight>
 
The sum of array elements is handled by an intrinsic.
[note: print is slsh-specific; if not available, use printf().]
 
<syntaxhighlight lang S="s-lang">print(sum(a));</langsyntaxhighlight>
 
The product is slightly more involved; I'll use this as a
chance to show the alternate stack-based use of 'foreach':
<langsyntaxhighlight Slang="s-lang">variable prod = a[0];
 
% Skipping the loop variable causes the val to be placed on the stack.
Line 2,610 ⟶ 3,268:
prod *= ();
 
print(prod);</langsyntaxhighlight>
 
=={{header|SAS}}==
<langsyntaxhighlight lang="sas">data _null_;
array a{*} a1-a100;
do i=1 to 100;
Line 2,620 ⟶ 3,278:
b=sum(of a{*});
put b c;
run;</langsyntaxhighlight>
 
=={{header|Sather}}==
<langsyntaxhighlight lang="sather">class MAIN is
main is
a :ARRAY{INT} := |10, 5, 5, 20, 60, 100|;
Line 2,632 ⟶ 3,290:
#OUT + sum + " " + prod + "\n";
end;
end;</langsyntaxhighlight>
 
=={{header|Scala}}==
<langsyntaxhighlight lang="scala">val seq = Seq(1, 2, 3, 4, 5)
val sum = seq.foldLeft(0)(_ + _)
val product = seq.foldLeft(1)(_ * _)</langsyntaxhighlight>
 
Or even shorter:
<langsyntaxhighlight lang="scala">val sum = seq.sum
val product = seq.product</langsyntaxhighlight>
 
Works with all data types for which a Numeric implicit is available.
 
=={{header|Scheme}}==
<langsyntaxhighlight lang="scheme">(apply + '(1 2 3 4 5))
(apply * '(1 2 3 4 5))</langsyntaxhighlight>
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.
<langsyntaxhighlight lang="scheme">(define (reduce f i l)
(if (null? l)
i
Line 2,655 ⟶ 3,313:
 
(reduce + 0 '(1 2 3 4 5)) ;; 0 is unit for +
(reduce * 1 '(1 2 3 4 5)) ;; 1 is unit for *</langsyntaxhighlight>
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">const func integer: sumArray (in array integer: valueArray) is func
result
var integer: sum is 0;
Line 2,678 ⟶ 3,336:
prod *:= value;
end for;
end func;</langsyntaxhighlight>
Call these functions with:
writeln(sumArray([](1, 2, 3, 4, 5)));
Line 2,684 ⟶ 3,342:
 
=={{header|SETL}}==
<langsyntaxhighlight SETLlang="setl">numbers := [1 2 3 4 5 6 7 8 9];
print(+/ numbers, */ numbers);</langsyntaxhighlight>
 
=> <code>45 362880</code>
Line 2,691 ⟶ 3,349:
=={{header|Sidef}}==
Using built-in methods:
<langsyntaxhighlight lang="ruby">var ary = [1, 2, 3, 4, 5];
say ary.sum; # => 15
say ary.prod; # => 120</langsyntaxhighlight>
 
Alternatively, using hyper-operators:
<langsyntaxhighlight lang="ruby">var ary = [1, 2, 3, 4, 5];
say ary«+»; # => 15
say ary«*»; # => 120</langsyntaxhighlight>
 
=={{header|Slate}}==
<langsyntaxhighlight lang="slate">#(1 2 3 4 5) reduce: [:sum :number | sum + number]
#(1 2 3 4 5) reduce: [:product :number | product * number]</langsyntaxhighlight>
Shorthand for the above with a macro:
<langsyntaxhighlight lang="slate">#(1 2 3 4 5) reduce: #+ `er
#(1 2 3 4 5) reduce: #* `er</langsyntaxhighlight>
 
=={{header|Smalltalk}}==
<langsyntaxhighlight 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]</langsyntaxhighlight>
Some implementation also provide a ''fold:'' message:
<langsyntaxhighlight lang="smalltalk">#(1 2 3 4 5) fold: [:sum :number | sum + number]
#(1 2 3 4 5) fold: [:product :number | product * number]</langsyntaxhighlight>
 
=={{header|SNOBOL4}}==
<langsyntaxhighlight lang="snobol"> t = table()
* read the integer from the std. input
init_tab t<x = x + 1> = trim(input) :s(init_tab)
Line 2,727 ⟶ 3,385:
out output = "Sum: " sum
output = "Prod: " product
end</langsyntaxhighlight>
 
Input
Line 2,740 ⟶ 3,398:
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}}==
<langsyntaxhighlight Sparklinglang="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</langsyntaxhighlight>
 
=={{header|Standard ML}}==
===Arrays===
<langsyntaxhighlight lang="sml">(* ints *)
val a = Array.fromList [1, 2, 3, 4, 5];
Array.foldl op+ 0 a;
Line 2,756 ⟶ 3,440:
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;</langsyntaxhighlight>
===Lists===
<langsyntaxhighlight lang="sml">(* ints *)
val x = [1, 2, 3, 4, 5];
foldl op+ 0 x;
Line 2,765 ⟶ 3,449:
val x = [1.0, 2.0, 3.0, 4.0, 5.0];
foldl op+ 0.0 x;
foldl op* 1.0 x;</langsyntaxhighlight>
 
=={{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:
 
<langsyntaxhighlight lang="stata">a = 1,-2,-3,-4,5
sum(a)
-3
(-1)^mod(sum(a:<0),2)*exp(sum(log(abs(a))))
-120</langsyntaxhighlight>
 
=={{header|Swift}}==
<langsyntaxhighlight lang="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</langsyntaxhighlight>
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl">set arr [list 3 6 8]
set sum [expr [join $arr +]]
set prod [expr [join $arr *]]</langsyntaxhighlight>
{{works with|Tcl|8.5}}
<langsyntaxhighlight lang="tcl">set arr [list 3 6 8]
set sum [tcl::mathop::+ {*}$arr]
set prod [tcl::mathop::* {*}$arr]</langsyntaxhighlight>
 
=={{header|TI-83 BASIC}}==
Use the built-in functions <code>sum()</code> and <code>prod()</code>.
<langsyntaxhighlight 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</langsyntaxhighlight>
 
=={{header|Toka}}==
<langsyntaxhighlight lang="toka">4 cells is-array foo
 
212 1 foo array.put
Line 2,814 ⟶ 3,498:
 
( product )
reset 1 4 0 [ i foo array.get * ] countedLoop .</langsyntaxhighlight>
 
=={{header|Trith}}==
<langsyntaxhighlight lang="trith">[1 2 3 4 5] 0 [+] foldl</langsyntaxhighlight>
<langsyntaxhighlight lang="trith">[1 2 3 4 5] 1 [*] foldl</langsyntaxhighlight>
 
 
=={{header|True BASIC}}==
{{works with|QBasic}}
<langsyntaxhighlight QBasiclang="qbasic">DIM array(1 TO 5)
DATA 1, 2, 3, 4, 5
FOR index = LBOUND(array) TO UBOUND(array)
Line 2,837 ⟶ 3,521:
PRINT "The sum is "; sum
PRINT "and the product is "; prod
END</langsyntaxhighlight>
 
 
=={{header|TUSCRIPT}}==
<langsyntaxhighlight lang="tuscript">
$$ MODE TUSCRIPT
list="1'2'3'4'5"
Line 2,852 ⟶ 3,536:
ENDLOOP
PRINT "product: ",product
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 2,863 ⟶ 3,547:
From an internal variable, $IFS delimited:
 
<langsyntaxhighlight lang="bash">sum=0
prod=1
list="1 2 3"
Line 2,869 ⟶ 3,553:
do sum="$(($sum + $n))"; prod="$(($prod * $n))"
done
echo $sum $prod</langsyntaxhighlight>
 
From the argument list (ARGV):
 
<langsyntaxhighlight lang="bash">sum=0
prod=1
for n
do sum="$(($sum + $n))"; prod="$(($prod * $n))"
done
echo $sum $prod</langsyntaxhighlight>
 
From STDIN, one integer per line:
 
<langsyntaxhighlight lang="bash">sum=0
prod=1
while read n
do sum="$(($sum + $n))"; prod="$(($prod * $n))"
done
echo $sum $prod</langsyntaxhighlight>
 
{{works with|GNUBourne bash|3.2.0(1)-releaseAgain (i386-unknown-freebsd6.1)SHell}}
{{works with|Korn Shell}}
From variable:
{{works with|Zsh}}
Using an actual array variable:
 
<langsyntaxhighlight lang="bash">LISTlist='(20 20 2');
SUM(( sum=0;, PRODprod=1; ))
for in in "$LIST{list[@]}"; do
SUM=$[$SUM +(( $i];sum PROD+=$[$PROD n, prod *= n $i];))
done;
printf '%d\t%d\n' "$sum" "$prod"
echo $SUM $PROD</lang>
</syntaxhighlight>
 
{{Out}}
<pre>42 800</pre>
 
=={{header|UnixPipes}}==
Uses [[ksh93]]-style process substitution.
{{works with|bash}}
<langsyntaxhighlight lang="bash">prod() {
(read B; res=$1; test -n "$B" && expr $res \* $B || echo $res)
}
Line 2,916 ⟶ 3,606:
 
(echo 3; echo 1; echo 4;echo 1;echo 5;echo 9) |
tee >(fold sum) >(fold prod) > /dev/null</langsyntaxhighlight>
 
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.
Line 2,922 ⟶ 3,612:
=={{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.
<langsyntaxhighlight lang="ursa">declare int<> stream
append 34 76 233 8 2 734 56 stream
 
Line 2,929 ⟶ 3,619:
 
# outputs 3.95961079808E11
out (* stream) endl console</langsyntaxhighlight>
 
=={{header|Ursala}}==
The reduction operator, :-, takes an associative binary function and a constant for the empty case.
Natural numbers are unsigned and of unlimited size.
<langsyntaxhighlight Ursalalang="ursala">#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></langsyntaxhighlight>
 
{{Out}}
Line 2,943 ⟶ 3,633:
 
=={{header|V}}==
<langsyntaxhighlight lang="v">[sp dup 0 [+] fold 'product=' put puts 1 [*] fold 'sum=' put puts].</langsyntaxhighlight>
 
{{Out|Using it}}
<langsyntaxhighlight lang="v">[1 2 3 4 5] sp
=
product=15
sum=120</langsyntaxhighlight>
 
=={{header|Vala}}==
<langsyntaxhighlight Valalang="vala">void main() {
int sum = 0, prod = 1;
int[] data = { 1, 2, 3, 4 };
Line 2,960 ⟶ 3,650:
}
print(@"sum: $(sum)\nproduct: $(prod)");
}</langsyntaxhighlight>
{{out}}
<pre>sum: 10
Line 2,967 ⟶ 3,657:
=={{header|VBA}}==
Assumes Excel is used.
<langsyntaxhighlight 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</langsyntaxhighlight>{{Out}}
<pre>sum : 55
product : 3628800</pre>
 
=={{header|VBScript}}==
<langsyntaxhighlight lang="vb">Function sum_and_product(arr)
sum = 0
product = 1
Line 2,992 ⟶ 3,682:
myarray = Array(1,2,3,4,5,6)
sum_and_product(myarray)
</syntaxhighlight>
</lang>
 
{{Out}}
Line 3,003 ⟶ 3,693:
{{trans|C#}}
 
<langsyntaxhighlight lang="vbnet">Module Program
Sub Main()
Dim arg As Integer() = {1, 2, 3, 4, 5}
Line 3,009 ⟶ 3,699:
Dim prod = arg.Aggregate(Function(runningProduct, nextFactor) runningProduct * nextFactor)
End Sub
End Module</langsyntaxhighlight>
 
=={{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>
 
{{out}}
<pre>
sum: 15
product: 120
</pre>
 
=={{header|Wart}}==
<langsyntaxhighlight lang="wart">def (sum_prod nums)
(list (+ @nums) (* @nums))</langsyntaxhighlight>
 
=={{header|WDTE}}==
<langsyntaxhighlight WDTElang="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 *;</langsyntaxhighlight>
 
=={{header|Wortel}}==
<langsyntaxhighlight lang="wortel">@sum [1 2 3 4] ; returns 10
@prod [1 2 3 4] ; returns 24</langsyntaxhighlight>
 
=={{header|Wren}}==
{{libheader|Wren-math}}
<langsyntaxhighlight ecmascriptlang="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))")</langsyntaxhighlight>
 
{{out}}
Line 3,042 ⟶ 3,751:
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">code CrLf=9, IntOut=11;
 
func SumProd(A, L);
Line 3,053 ⟶ 3,762:
]; \SumSq
 
SumProd([1,2,3,4,5,6,7,8,9,10], 10)</langsyntaxhighlight>
 
{{Out}}
Line 3,064 ⟶ 3,773:
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.
 
<langsyntaxhighlight lang="xml"><xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" />
Line 3,099 ⟶ 3,808:
</xsl:call-template>
</xsl:template>
</xsl:stylesheet></langsyntaxhighlight>
 
 
=={{header|Yabasic}}==
{{trans|QBasic}}
<langsyntaxhighlight lang="yabasic">dim array(5)
data 1, 2, 3, 4, 5
for index = 1 to arraysize(array(), 1)
Line 3,118 ⟶ 3,827:
print "The sum is ", sum //15
print "and the product is ", prod //120
end</langsyntaxhighlight>
 
=={{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}}==
{{trans|Clojure}}
<langsyntaxhighlight lang="zkl">fcn sum(vals){vals.reduce('+,0)}
fcn product(vals){vals.reduce('*,1)}</langsyntaxhighlight>
<pre>
sum(T(1,2,3,4)) //-->10
Line 3,131 ⟶ 3,852:
 
=={{header|Zoea}}==
<syntaxhighlight lang="zoea">
<lang Zoea>
program: sum_and_product
case: 1
Line 3,139 ⟶ 3,860:
input: [2,3,4]
output: [9,24]
</syntaxhighlight>
</lang>
 
=={{header|Zoea Visual}}==
885

edits