Sum and product of an array: Difference between revisions
Content added Content deleted
(→{{header|LOLCODE}}: Add implementation.) |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
Line 7: | Line 7: | ||
=={{header|11l}}== |
=={{header|11l}}== |
||
< |
<syntaxhighlight lang="11l">V arr = [1, 2, 3, 4] |
||
print(sum(arr)) |
print(sum(arr)) |
||
print(product(arr))</ |
print(product(arr))</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 18: | Line 18: | ||
=={{header|360 Assembly}}== |
=={{header|360 Assembly}}== |
||
< |
<syntaxhighlight lang="360asm">* Sum and product of an array 20/04/2017 |
||
SUMPROD CSECT |
SUMPROD CSECT |
||
USING SUMPROD,R15 base register |
USING SUMPROD,R15 base register |
||
Line 38: | Line 38: | ||
PG DS CL24 buffer |
PG DS CL24 buffer |
||
YREGS |
YREGS |
||
END SUMPROD</ |
END SUMPROD</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 45: | Line 45: | ||
=={{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 60: | Line 60: | ||
$sum:=sum($list) |
$sum:=sum($list) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|ACL2}}== |
=={{header|ACL2}}== |
||
< |
<syntaxhighlight lang="lisp">(defun sum (xs) |
||
(if (endp xs) |
(if (endp xs) |
||
0 |
0 |
||
Line 73: | Line 73: | ||
1 |
1 |
||
(* (first xs) |
(* (first xs) |
||
(prod (rest xs)))))</ |
(prod (rest xs)))))</syntaxhighlight> |
||
=={{header|Action!}}== |
=={{header|Action!}}== |
||
< |
<syntaxhighlight lang="action!">DEFINE LAST="6" |
||
PROC Main() |
PROC Main() |
||
Line 110: | Line 110: | ||
OD |
OD |
||
PrintIE(res) |
PrintIE(res) |
||
RETURN</ |
RETURN</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Sum_and_product_of_an_array.png Screenshot from Atari 8-bit computer] |
[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: | Line 119: | ||
=={{header|ActionScript}}== |
=={{header|ActionScript}}== |
||
< |
<syntaxhighlight lang="actionscript">package { |
||
import flash.display.Sprite; |
import flash.display.Sprite; |
||
Line 140: | Line 140: | ||
} |
} |
||
} |
} |
||
}</ |
}</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 149: | Line 149: | ||
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 158: | Line 158: | ||
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}}== |
=={{header|Aime}}== |
||
< |
<syntaxhighlight lang="aime">void |
||
compute(integer &s, integer &p, list l) |
compute(integer &s, integer &p, list l) |
||
{ |
{ |
||
Line 185: | Line 185: | ||
return 0; |
return 0; |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>77 |
<pre>77 |
||
Line 191: | Line 191: | ||
=={{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 211: | Line 211: | ||
) # 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}} |
{{Out}} |
||
<pre> |
<pre> |
||
Line 218: | Line 218: | ||
=={{header|ALGOL W}}== |
=={{header|ALGOL W}}== |
||
< |
<syntaxhighlight lang="algolw">begin |
||
% computes the sum and product of intArray % |
% computes the sum and product of intArray % |
||
Line 251: | Line 251: | ||
write( sum, product ); |
write( sum, product ); |
||
end |
end |
||
end.</ |
end.</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 260: | Line 260: | ||
=={{header|APL}}== |
=={{header|APL}}== |
||
{{works with|APL2}} |
{{works with|APL2}} |
||
< |
<syntaxhighlight lang="apl"> sum ← +/ ⍝ sum (+) over (/) an array |
||
prod ← ×/ ⍝ product (×) over (/) an array |
prod ← ×/ ⍝ product (×) over (/) an array |
||
Line 269: | Line 269: | ||
prod a ⍝ or simply: ×/a |
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. |
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. |
||
Line 276: | Line 276: | ||
{{works with|Extended Dyalog APL}} ([https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn//1HfVIVHbRMUNLT1FR71rlM4PF1fU8FQwUjBWMFEwfT/fwA 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 |
using the [https://aplwiki.com/wiki/Pair pair (⍮)] primitive function |
||
< |
<syntaxhighlight lang="apl"> ⎕ ← (+/ ⍮ ×/) 1 2 3 4 5 |
||
15 120</ |
15 120</syntaxhighlight> |
||
Spaces are optional except as separators between array elements. |
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 287: | Line 287: | ||
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 : |
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} |
set {array, sum, product} to {{1, 2, 3, 4, 5}, 0, 1} |
||
repeat with i in array |
repeat with i in array |
||
Line 296: | Line 296: | ||
end repeat |
end repeat |
||
return sum & " , " & product as string |
return sum & " , " & product as string |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 304: | Line 304: | ||
Or, using an AppleScript implementation of '''fold'''/'''reduce''': |
Or, using an AppleScript implementation of '''fold'''/'''reduce''': |
||
< |
<syntaxhighlight lang="applescript">on summed(a, b) |
||
a + b |
a + b |
||
end summed |
end summed |
||
Line 363: | Line 363: | ||
end script |
end script |
||
end if |
end if |
||
end mReturn</ |
end mReturn</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
< |
<syntaxhighlight lang="applescript">{{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, {sum:55}, {product:3628800}}</syntaxhighlight> |
||
=={{header|Arturo}}== |
=={{header|Arturo}}== |
||
< |
<syntaxhighlight lang="rebol">arr: 1..10 |
||
print ["Sum =" sum arr] |
print ["Sum =" sum arr] |
||
print ["Product =" product arr]</ |
print ["Product =" product arr]</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 379: | Line 379: | ||
=={{header|Asymptote}}== |
=={{header|Asymptote}}== |
||
< |
<syntaxhighlight lang="asymptote">int[] matriz = {1,2,3,4,5}; |
||
int suma = 0, prod = 1; |
int suma = 0, prod = 1; |
||
Line 387: | Line 387: | ||
} |
} |
||
write("Sum = ", suma); |
write("Sum = ", suma); |
||
write("Product = ", prod);</ |
write("Product = ", prod);</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>Sum = 15 |
<pre>Sum = 15 |
||
Line 393: | Line 393: | ||
=={{header|AutoHotkey}}== |
=={{header|AutoHotkey}}== |
||
< |
<syntaxhighlight lang="autohotkey">numbers = 1,2,3,4,5 |
||
product := 1 |
product := 1 |
||
loop, parse, numbers, `, |
loop, parse, numbers, `, |
||
Line 400: | Line 400: | ||
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 410: | Line 410: | ||
$ 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 425: | Line 425: | ||
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 447: | Line 447: | ||
{ * } |
{ * } |
||
{ 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 460: | Line 460: | ||
=={{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 467: | Line 467: | ||
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}} |
{{works with|Commodore BASIC}} |
||
< |
<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) |
||
Line 479: | Line 479: | ||
70 S = S + A(I):P = P * A(I) |
70 S = S + A(I):P = P * A(I) |
||
80 NEXT |
80 NEXT |
||
90 PRINT "SUM="S,"PRODUCT="P</ |
90 PRINT "SUM="S,"PRODUCT="P</syntaxhighlight> |
||
==={{header|Atari BASIC}}=== |
==={{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: |
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 |
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) |
||
Line 492: | Line 492: | ||
70 S = S + A(I):P = P * A(I) |
70 S = S + A(I):P = P * A(I) |
||
80 NEXT I |
80 NEXT I |
||
90 PRINT "SUM=";S,"PRODUCT=";P</ |
90 PRINT "SUM=";S,"PRODUCT=";P</syntaxhighlight> |
||
==={{header|BaCon}}=== |
==={{header|BaCon}}=== |
||
< |
<syntaxhighlight lang="freebasic"> |
||
'--- set some values into the array |
'--- set some values into the array |
||
DECLARE a[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10 } TYPE int |
DECLARE a[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10 } TYPE int |
||
Line 511: | Line 511: | ||
PRINT "The sum is ",sum |
PRINT "The sum is ",sum |
||
PRINT "The product is ",product |
PRINT "The product is ",product |
||
</ |
</syntaxhighlight> |
||
==={{header|BBC BASIC}}=== |
==={{header|BBC BASIC}}=== |
||
< |
<syntaxhighlight lang="bbcbasic"> DIM array%(5) |
||
array%() = 1, 2, 3, 4, 5, 6 |
array%() = 1, 2, 3, 4, 5, 6 |
||
Line 523: | Line 523: | ||
product% *= array%(I%) |
product% *= array%(I%) |
||
NEXT |
NEXT |
||
PRINT "Product of array elements = " ; product%</ |
PRINT "Product of array elements = " ; product%</syntaxhighlight> |
||
==={{header|IS-BASIC}}=== |
==={{header|IS-BASIC}}=== |
||
< |
<syntaxhighlight lang="is-basic">100 RANDOMIZE |
||
110 LET N=5 |
110 LET N=5 |
||
120 NUMERIC A(1 TO N) |
120 NUMERIC A(1 TO N) |
||
Line 538: | Line 538: | ||
200 LET SUM=SUM+A(I):LET PROD=PROD*A(I) |
200 LET SUM=SUM+A(I):LET PROD=PROD*A(I) |
||
210 NEXT |
210 NEXT |
||
220 PRINT "Sum =";SUM,"Product =";PROD</ |
220 PRINT "Sum =";SUM,"Product =";PROD</syntaxhighlight> |
||
=={{header|BASIC256}}== |
=={{header|BASIC256}}== |
||
{{trans|Yabasic}} |
{{trans|Yabasic}} |
||
< |
<syntaxhighlight lang="basic256">arraybase 1 |
||
dim array(5) |
dim array(5) |
||
array[1] = 1 |
array[1] = 1 |
||
Line 559: | Line 559: | ||
print "The sum is "; sum #15 |
print "The sum is "; sum #15 |
||
print "and the product is "; prod #120 |
print "and the product is "; prod #120 |
||
end</ |
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 576: | Line 576: | ||
} |
} |
||
"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}}== |
=={{header|BQN}}== |
||
Line 592: | Line 592: | ||
* Paired with <code>⋈</code> |
* Paired with <code>⋈</code> |
||
* Product <code>×´</code> |
* Product <code>×´</code> |
||
< |
<syntaxhighlight lang="bqn"> SumProd ← +´⋈×´ |
||
+´⋈×´ |
+´⋈×´ |
||
SumProd 1‿2‿3‿4‿5 |
SumProd 1‿2‿3‿4‿5 |
||
⟨ 15 120 ⟩</ |
⟨ 15 120 ⟩</syntaxhighlight> |
||
=={{header|Bracmat}}== |
=={{header|Bracmat}}== |
||
< |
<syntaxhighlight lang="bracmat">( ( sumprod |
||
= sum prod num |
= sum prod num |
||
. 0:?sum |
. 0:?sum |
||
Line 614: | Line 614: | ||
) |
) |
||
& out$sumprod$(2 3 5 7 11 13 17 19) |
& out$sumprod$(2 3 5 7 11 13 17 19) |
||
);</ |
);</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
<pre>77.9699690</pre> |
<pre>77.9699690</pre> |
||
=={{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 629: | Line 629: | ||
sum += *p; |
sum += *p; |
||
prod *= *p; |
prod *= *p; |
||
}</ |
}</syntaxhighlight> |
||
=={{header|C sharp|C#}}== |
=={{header|C sharp|C#}}== |
||
< |
<syntaxhighlight lang="csharp">int sum = 0, prod = 1; |
||
int[] arg = { 1, 2, 3, 4, 5 }; |
int[] arg = { 1, 2, 3, 4, 5 }; |
||
foreach (int value in arg) { |
foreach (int value in arg) { |
||
sum += value; |
sum += value; |
||
prod *= value; |
prod *= value; |
||
}</ |
}</syntaxhighlight> |
||
===Alternative using Linq (C# 3)=== |
===Alternative using Linq (C# 3)=== |
||
{{works with|C sharp|C#|3}} |
{{works with|C sharp|C#|3}} |
||
< |
<syntaxhighlight lang="csharp">int[] arg = { 1, 2, 3, 4, 5 }; |
||
int sum = arg.Sum(); |
int sum = arg.Sum(); |
||
int prod = arg.Aggregate((runningProduct, nextFactor) => runningProduct * nextFactor);</ |
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 656: | Line 656: | ||
// 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 685: | Line 685: | ||
cout << sum(aflo,4) << " " << prod(aflo,4) << endl; |
cout << sum(aflo,4) << " " << prod(aflo,4) << endl; |
||
return 0; |
return 0; |
||
}</ |
}</syntaxhighlight> |
||
=={{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 711: | Line 711: | ||
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}}== |
=={{header|CLU}}== |
||
< |
<syntaxhighlight lang="clu">sum_and_product = proc (a: array[int]) returns (int,int) signals (overflow) |
||
sum: int := 0 |
sum: int := 0 |
||
prod: int := 1 |
prod: int := 1 |
||
Line 742: | Line 742: | ||
stream$putl(po, "Sum = " || int$unparse(sum)) |
stream$putl(po, "Sum = " || int$unparse(sum)) |
||
stream$putl(po, "Product = " || int$unparse(prod)) |
stream$putl(po, "Product = " || int$unparse(prod)) |
||
end start_up</ |
end start_up</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>Sum = 55 |
<pre>Sum = 55 |
||
Line 748: | Line 748: | ||
=={{header|COBOL}}== |
=={{header|COBOL}}== |
||
< |
<syntaxhighlight lang="cobol"> IDENTIFICATION DIVISION. |
||
PROGRAM-ID. array-sum-and-product. |
PROGRAM-ID. array-sum-and-product. |
||
Line 772: | Line 772: | ||
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 781: | Line 781: | ||
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}}== |
=={{header|Crystal}}== |
||
===Declarative=== |
===Declarative=== |
||
<syntaxhighlight lang="ruby"> |
|||
<lang Ruby> |
|||
def sum_product(a) |
def sum_product(a) |
||
{ a.sum(), a.product() } |
{ a.sum(), a.product() } |
||
end |
end |
||
</syntaxhighlight> |
|||
</lang> |
|||
===Imperative=== |
===Imperative=== |
||
<syntaxhighlight lang="ruby"> |
|||
<lang Ruby> |
|||
def sum_product_imperative(a) |
def sum_product_imperative(a) |
||
sum, product = 0, 1 |
sum, product = 0, 1 |
||
Line 823: | Line 823: | ||
{sum, product} |
{sum, product} |
||
end |
end |
||
</syntaxhighlight> |
|||
</lang> |
|||
<syntaxhighlight lang="ruby"> |
|||
<lang Ruby> |
|||
require "benchmark" |
require "benchmark" |
||
Benchmark.ips do |x| |
Benchmark.ips do |x| |
||
Line 831: | Line 831: | ||
x.report("imperative") { sum_product_imperative [1, 2, 3, 4, 5] } |
x.report("imperative") { sum_product_imperative [1, 2, 3, 4, 5] } |
||
end |
end |
||
</syntaxhighlight> |
|||
</lang> |
|||
<pre>declarative 8.1M (123.45ns) (± 2.99%) 65 B/op 1.30× slower |
<pre>declarative 8.1M (123.45ns) (± 2.99%) 65 B/op 1.30× slower |
||
Line 837: | Line 837: | ||
=={{header|D}}== |
=={{header|D}}== |
||
< |
<syntaxhighlight lang="d">import std.stdio; |
||
void main() { |
void main() { |
||
Line 852: | Line 852: | ||
writeln("Sum: ", sum); |
writeln("Sum: ", sum); |
||
writeln("Product: ", prod); |
writeln("Product: ", prod); |
||
}</ |
}</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
<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 867: | Line 867: | ||
writeln("Sum: ", r[0]); |
writeln("Sum: ", r[0]); |
||
writeln("Product: ", r[1]); |
writeln("Product: ", r[1]); |
||
}</ |
}</syntaxhighlight> |
||
=={{header|dc}}== |
=={{header|dc}}== |
||
< |
<syntaxhighlight lang="dc">1 3 5 7 9 11 13 0ss1sp[dls+sslp*spz0!=a]dsax[Sum: ]Plsp[Product: ]Plpp |
||
Sum: 49 |
Sum: 49 |
||
Product: 135135</ |
Product: 135135</syntaxhighlight> |
||
=={{header|Delphi}}== |
=={{header|Delphi}}== |
||
< |
<syntaxhighlight lang="delphi">program SumAndProductOfArray; |
||
{$APPTYPE CONSOLE} |
{$APPTYPE CONSOLE} |
||
Line 895: | Line 895: | ||
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|Eiffel}}== |
=={{header|Eiffel}}== |
||
< |
<syntaxhighlight lang="eiffel"> |
||
class |
class |
||
APPLICATION |
APPLICATION |
||
Line 945: | Line 945: | ||
end |
end |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{Out}} |
{{Out}} |
||
<pre>Sum of the elements of the array: 30 |
<pre>Sum of the elements of the array: 30 |
||
Line 952: | Line 952: | ||
=={{header|Elena}}== |
=={{header|Elena}}== |
||
ELENA 5.0: |
ELENA 5.0: |
||
< |
<syntaxhighlight lang="elena">import system'routines; |
||
import extensions; |
import extensions; |
||
Line 961: | Line 961: | ||
var sum := list.summarize(new Integer()); |
var sum := list.summarize(new Integer()); |
||
var product := list.accumulate(new Integer(1), (var,val => var * val)); |
var product := list.accumulate(new Integer(1), (var,val => var * val)); |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Elixir}}== |
=={{header|Elixir}}== |
||
When an accumulator is omitted, the first element of the collection is used as the initial value of acc. |
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 |
15 |
||
iex(27)> Enum.reduce([1,2,3,4,5], 1, fn x,acc -> x*acc end) |
iex(27)> Enum.reduce([1,2,3,4,5], 1, fn x,acc -> x*acc end) |
||
Line 982: | Line 982: | ||
iex(32)> Enum.reduce([], fn x,acc -> x*acc end) |
iex(32)> Enum.reduce([], fn x,acc -> x*acc end) |
||
** (Enum.EmptyError) empty error |
** (Enum.EmptyError) empty error |
||
(elixir) lib/enum.ex:1287: Enum.reduce/2</ |
(elixir) lib/enum.ex:1287: Enum.reduce/2</syntaxhighlight> |
||
The function with sum |
The function with sum |
||
< |
<syntaxhighlight lang="elixir">Enum.sum([1,2,3,4,5]) #=> 15</syntaxhighlight> |
||
=={{header|Emacs Lisp}}== |
=={{header|Emacs Lisp}}== |
||
< |
<syntaxhighlight lang="lisp">(let ((array [1 2 3 4 5])) |
||
(apply #'+ (append array nil)) |
(apply #'+ (append array nil)) |
||
(apply #'* (append array nil)))</ |
(apply #'* (append array nil)))</syntaxhighlight> |
||
{{libheader|cl-lib}} |
{{libheader|cl-lib}} |
||
< |
<syntaxhighlight lang="lisp">(require 'cl-lib) |
||
(let ((array [1 2 3 4 5])) |
(let ((array [1 2 3 4 5])) |
||
(cl-reduce #'+ array) |
(cl-reduce #'+ array) |
||
(cl-reduce #'* array))</ |
(cl-reduce #'* array))</syntaxhighlight> |
||
{{libheader|seq.el}} |
{{libheader|seq.el}} |
||
< |
<syntaxhighlight lang="lisp">(require 'seq) |
||
(let ((array [1 2 3 4 5])) |
(let ((array [1 2 3 4 5])) |
||
(seq-reduce #'+ array 0) |
(seq-reduce #'+ array 0) |
||
(seq-reduce #'* array 1))</ |
(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 1,036: | Line 1,036: | ||
Acc; |
Acc; |
||
sum_tail([Head|Tail], Acc) -> |
sum_tail([Head|Tail], Acc) -> |
||
sum_tail(Tail, Head + Acc).</ |
sum_tail(Tail, Head + Acc).</syntaxhighlight> |
||
=={{header|Euphoria}}== |
=={{header|Euphoria}}== |
||
< |
<syntaxhighlight lang="euphoria">sequence array |
||
integer sum,prod |
integer sum,prod |
||
Line 1,052: | Line 1,052: | ||
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}} |
{{Out}} |
||
Line 1,061: | Line 1,061: | ||
=={{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.reduce (*) |
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 1,086: | Line 1,086: | ||
"Sum: "s;." |
"Sum: "s;." |
||
Product: "p;.</ |
Product: "p;.</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>Sum: 15 |
<pre>Sum: 15 |
||
Line 1,093: | Line 1,093: | ||
=={{header|Fantom}}== |
=={{header|Fantom}}== |
||
< |
<syntaxhighlight lang="fantom"> |
||
class Main |
class Main |
||
{ |
{ |
||
Line 1,126: | Line 1,126: | ||
} |
} |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Fermat}}== |
=={{header|Fermat}}== |
||
< |
<syntaxhighlight lang="fermat"> |
||
[a]:=[(1,1,2,3,5,8,13)]; |
[a]:=[(1,1,2,3,5,8,13)]; |
||
!!Sigma<i=1,7>[a[i]]; |
!!Sigma<i=1,7>[a[i]]; |
||
!!Prod<i=1,7>[a[i]]; |
!!Prod<i=1,7>[a[i]]; |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,141: | Line 1,141: | ||
=={{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 1,148: | Line 1,148: | ||
' + 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}}== |
=={{header|FreeBASIC}}== |
||
< |
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64 |
||
Dim a(1 To 4) As Integer = {1, 4, 6, 3} |
Dim a(1 To 4) As Integer = {1, 4, 6, 3} |
||
Line 1,171: | Line 1,171: | ||
Print |
Print |
||
Print "Press any key to quit" |
Print "Press any key to quit" |
||
Sleep</ |
Sleep</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,180: | Line 1,180: | ||
=={{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|Fōrmulæ}}== |
=={{header|Fōrmulæ}}== |
||
Line 1,196: | Line 1,196: | ||
=={{header|Gambas}}== |
=={{header|Gambas}}== |
||
'''[https://gambas-playground.proko.eu/?gist=4a4bdc35d661e2dc22d66d88991bef95 Click this link to run this code]''' |
'''[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 iList As Integer[] = [1, 2, 3, 4, 5] |
||
Dim iSum, iCount As Integer |
Dim iSum, iCount As Integer |
||
Line 1,209: | Line 1,209: | ||
Print "The Product =\t" & iPrd |
Print "The Product =\t" & iPrd |
||
End</ |
End</syntaxhighlight> |
||
Output: |
Output: |
||
<pre> |
<pre> |
||
Line 1,217: | Line 1,217: | ||
=={{header|GAP}}== |
=={{header|GAP}}== |
||
< |
<syntaxhighlight lang="gap">v := [1 .. 8]; |
||
Sum(v); |
Sum(v); |
||
Line 1,231: | Line 1,231: | ||
Product(v, n -> 1/n); |
Product(v, n -> 1/n); |
||
# 1/40320</ |
# 1/40320</syntaxhighlight> |
||
=={{header|GFA Basic}}== |
=={{header|GFA Basic}}== |
||
< |
<syntaxhighlight lang="basic"> |
||
DIM a%(10) |
DIM a%(10) |
||
' put some values into the array |
' put some values into the array |
||
Line 1,251: | Line 1,251: | ||
PRINT "Sum is ";sum% |
PRINT "Sum is ";sum% |
||
PRINT "Product is ";product% |
PRINT "Product is ";product% |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Go}}== |
=={{header|Go}}== |
||
;Implementation |
;Implementation |
||
< |
<syntaxhighlight lang="go">package main |
||
import "fmt" |
import "fmt" |
||
Line 1,266: | Line 1,266: | ||
} |
} |
||
fmt.Println(sum, prod) |
fmt.Println(sum, prod) |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,272: | Line 1,272: | ||
</pre> |
</pre> |
||
;Library |
;Library |
||
< |
<syntaxhighlight lang="go">package main |
||
import ( |
import ( |
||
Line 1,285: | Line 1,285: | ||
fmt.Println("Sum: ", floats.Sum(a)) |
fmt.Println("Sum: ", floats.Sum(a)) |
||
fmt.Println("Product:", floats.Prod(a)) |
fmt.Println("Product:", floats.Prod(a)) |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,294: | Line 1,294: | ||
=={{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}}== |
||
Line 1,306: | Line 1,306: | ||
{{works with|QBasic}} |
{{works with|QBasic}} |
||
< |
<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 1,318: | Line 1,318: | ||
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 |
||
Line 1,328: | Line 1,328: | ||
s1 = foldl (+) 0 values -- the hard way |
s1 = foldl (+) 0 values -- the hard way |
||
p1 = foldl (*) 1 values</ |
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: |
Or perhaps: |
||
< |
<syntaxhighlight lang="haskell">import Data.Array (listArray, elems) |
||
main :: IO () |
main :: IO () |
||
main = mapM_ print $ [sum, product] <*> [elems $ listArray (1, 10) [11 .. 20]]</ |
main = mapM_ print $ [sum, product] <*> [elems $ listArray (1, 10) [11 .. 20]]</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
<pre>155 |
<pre>155 |
||
Line 1,347: | Line 1,347: | ||
=={{header|HicEst}}== |
=={{header|HicEst}}== |
||
< |
<syntaxhighlight lang="hicest">array = $ ! 1, 2, ..., LEN(array) |
||
sum = SUM(array) |
sum = SUM(array) |
||
Line 1,356: | Line 1,356: | ||
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|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}}== |
=={{header|IDL}}== |
||
< |
<syntaxhighlight lang="idl">array = [3,6,8] |
||
print,total(array) |
print,total(array) |
||
print,product(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 1,383: | Line 1,383: | ||
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:< |
Simple approach:<syntaxhighlight lang="j"> (+/,*/) 2 3 5 7 |
||
17 210</ |
17 210</syntaxhighlight> |
||
<hr /> |
<hr /> |
||
Line 1,394: | Line 1,394: | ||
Longer exposition: |
Longer exposition: |
||
< |
<syntaxhighlight lang="j">sum =: +/ |
||
product =: */</ |
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 1,420: | Line 1,420: | ||
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 1,437: | Line 1,437: | ||
} |
} |
||
} |
} |
||
}</ |
}</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 1,451: | Line 1,451: | ||
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 1,461: | Line 1,461: | ||
=={{header|JavaScript}}== |
=={{header|JavaScript}}== |
||
===ES5=== |
===ES5=== |
||
< |
<syntaxhighlight lang="javascript">var array = [1, 2, 3, 4, 5], |
||
sum = 0, |
sum = 0, |
||
prod = 1, |
prod = 1, |
||
Line 1,469: | Line 1,469: | ||
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 1,481: | Line 1,481: | ||
return a * b; |
return a * b; |
||
}, 1); |
}, 1); |
||
alert(sum + ' ' + prod);</ |
alert(sum + ' ' + prod);</syntaxhighlight> |
||
===ES6=== |
===ES6=== |
||
< |
<syntaxhighlight lang="javascript">(() => { |
||
'use strict'; |
'use strict'; |
||
Line 1,502: | Line 1,502: | ||
.map(f => f([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])) |
.map(f => f([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])) |
||
); |
); |
||
})();</ |
})();</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
Line 1,512: | Line 1,512: | ||
=={{header|jq}}== |
=={{header|jq}}== |
||
The builtin filter, add/0, computes the sum of an array: |
The builtin filter, add/0, computes the sum of an array: |
||
< |
<syntaxhighlight lang="jq">[4,6,8] | add |
||
# => 18</ |
# => 18</syntaxhighlight> |
||
< |
<syntaxhighlight lang="jq">[range(2;5) * 2] | add |
||
# => 18</ |
# => 18</syntaxhighlight> |
||
An efficient companion filter for computing the product of the items in an array can be defined as follows: |
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: |
Examples: |
||
< |
<syntaxhighlight lang="jq">[4,6,8] | prod |
||
# => 192</ |
# => 192</syntaxhighlight> |
||
10! |
10! |
||
< |
<syntaxhighlight lang="jq">[range(1;11)] | prod |
||
# =>3628800</ |
# =>3628800</syntaxhighlight> |
||
=={{header|Julia}}== |
=={{header|Julia}}== |
||
< |
<syntaxhighlight lang="julia">julia> sum([4,6,8]) |
||
18 |
18 |
||
Line 1,536: | Line 1,536: | ||
julia> prod([4,6,8]) |
julia> prod([4,6,8]) |
||
192</ |
192</syntaxhighlight> |
||
=={{header|K}}== |
=={{header|K}}== |
||
< |
<syntaxhighlight lang="k"> sum: {+/}x |
||
product: {*/}x |
product: {*/}x |
||
a: 1 3 5 7 9 11 13 |
a: 1 3 5 7 9 11 13 |
||
Line 1,545: | Line 1,545: | ||
49 |
49 |
||
product a |
product a |
||
135135</ |
135135</syntaxhighlight> |
||
It is easy to see the relationship of K to J here. |
It is easy to see the relationship of K to J here. |
||
=={{header|Kotlin}}== |
=={{header|Kotlin}}== |
||
< |
<syntaxhighlight lang="scala">// version 1.1.2 |
||
fun main(args: Array<String>) { |
fun main(args: Array<String>) { |
||
Line 1,559: | Line 1,559: | ||
val product = a.fold(1) { acc, i -> acc * i } |
val product = a.fold(1) { acc, i -> acc * i } |
||
println("Product is $product") |
println("Product is $product") |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,570: | Line 1,570: | ||
=={{header|Lambdatalk}}== |
=={{header|Lambdatalk}}== |
||
< |
<syntaxhighlight lang="lisp"> |
||
{A.serie start end [step]} creates a sequence from start to end with optional step |
{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.new words} creates an array from a sequence of words |
||
Line 1,586: | Line 1,586: | ||
9332621544394415268169923885626670049071596826438162146859296389521759999322991 |
9332621544394415268169923885626670049071596826438162146859296389521759999322991 |
||
5608941463976156518286253697920827223758251185210916864000000000000000000000000 |
5608941463976156518286253697920827223758251185210916864000000000000000000000000 |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Lang5}}== |
=={{header|Lang5}}== |
||
< |
<syntaxhighlight lang="lang5">4 iota 1 + dup |
||
'+ reduce |
'+ reduce |
||
'* reduce</ |
'* reduce</syntaxhighlight> |
||
=={{header|langur}}== |
=={{header|langur}}== |
||
< |
<syntaxhighlight lang="langur">val .arr = series 19 |
||
writeln " array: ", .arr |
writeln " array: ", .arr |
||
writeln " sum: ", fold f .x + .y, .arr |
writeln " sum: ", fold f .x + .y, .arr |
||
writeln "product: ", fold f .x x .y, .arr</ |
writeln "product: ", fold f .x x .y, .arr</syntaxhighlight> |
||
{{works with|langur|0.6.6}} |
{{works with|langur|0.6.6}} |
||
< |
<syntaxhighlight lang="langur">val .arr = series 19 |
||
writeln " array: ", .arr |
writeln " array: ", .arr |
||
writeln " sum: ", fold f{+}, .arr |
writeln " sum: ", fold f{+}, .arr |
||
writeln "product: ", fold f{x}, .arr</ |
writeln "product: ", fold f{x}, .arr</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,612: | Line 1,612: | ||
=={{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 1,622: | Line 1,622: | ||
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 1,628: | Line 1,628: | ||
=={{header|Liberty BASIC}}== |
=={{header|Liberty BASIC}}== |
||
< |
<syntaxhighlight lang="lb">Dim array(19) |
||
For i = 0 To 19 |
For i = 0 To 19 |
||
Line 1,642: | Line 1,642: | ||
Print "Sum is " + str$(sum) |
Print "Sum is " + str$(sum) |
||
Print "Product is " + str$(product)</ |
Print "Product is " + str$(product)</syntaxhighlight> |
||
=={{header|Lingo}}== |
=={{header|Lingo}}== |
||
< |
<syntaxhighlight lang="lingo">on sum (intList) |
||
res = 0 |
res = 0 |
||
repeat with v in intList |
repeat with v in intList |
||
Line 1,659: | Line 1,659: | ||
end repeat |
end repeat |
||
return res |
return res |
||
end</ |
end</syntaxhighlight> |
||
=={{header|LiveCode}}== |
=={{header|LiveCode}}== |
||
< |
<syntaxhighlight lang="livecode">//sum |
||
put "1,2,3,4" into nums |
put "1,2,3,4" into nums |
||
split nums using comma |
split nums using comma |
||
Line 1,676: | Line 1,676: | ||
end if |
end if |
||
end repeat |
end repeat |
||
answer prodnums</ |
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}}== |
=={{header|LOLCODE}}== |
||
< |
<syntaxhighlight lang="lolcode">HAI 1.2 |
||
I HAS A Nums ITZ A BUKKIT |
I HAS A Nums ITZ A BUKKIT |
||
Nums HAS A Length ITZ 0 |
Nums HAS A Length ITZ 0 |
||
Line 1,709: | Line 1,709: | ||
VISIBLE "Product = " ! |
VISIBLE "Product = " ! |
||
VISIBLE Timesed |
VISIBLE Timesed |
||
KTHXBYE</ |
KTHXBYE</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
Line 1,716: | Line 1,716: | ||
=={{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 1,723: | Line 1,723: | ||
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) |
function table.sum(arr, length) |
||
--same as if <> then <> else <> |
--same as if <> then <> else <> |
||
Line 1,738: | Line 1,738: | ||
print(table.sum(t,#t)) |
print(table.sum(t,#t)) |
||
print(table.product(t,3)) |
print(table.product(t,3)) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{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|M2000 Interpreter}}== |
=={{header|M2000 Interpreter}}== |
||
<syntaxhighlight lang="m2000 interpreter"> |
|||
<lang M2000 Interpreter> |
|||
Module Checkit { |
Module Checkit { |
||
a = (1,2,3,4,5,6,7,8,9,10) |
a = (1,2,3,4,5,6,7,8,9,10) |
||
Line 1,761: | Line 1,761: | ||
} |
} |
||
checkit |
checkit |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Maple}}== |
=={{header|Maple}}== |
||
< |
<syntaxhighlight lang="maple">a := Array([1, 2, 3, 4, 5, 6]); |
||
add(a); |
add(a); |
||
mul(a);</ |
mul(a);</syntaxhighlight> |
||
=={{header|Mathematica}}/{{header|Wolfram Language}}== |
=={{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 1,777: | Line 1,777: | ||
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 1,790: | Line 1,790: | ||
Sample Usage: |
Sample Usage: |
||
< |
<syntaxhighlight lang="matlab">>> array = [1 2 3;4 5 6;7 8 9] |
||
array = |
array = |
||
Line 1,824: | Line 1,824: | ||
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}}== |
=={{header|min}}== |
||
{{works with|min|0.19.3}} |
{{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</ |
"Sum: $1\nProduct: $2" get-stack % puts</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,852: | Line 1,852: | ||
=={{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,874: | Line 1,874: | ||
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}} |
{{Out}} |
||
<pre>Sum of array: 15 |
<pre>Sum of array: 15 |
||
Line 1,880: | Line 1,880: | ||
=={{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,892: | Line 1,892: | ||
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,913: | Line 1,913: | ||
=={{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,942: | Line 1,942: | ||
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,969: | Line 1,969: | ||
return |
return |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{Out}} |
{{Out}} |
||
<pre> |
<pre> |
||
Line 1,978: | Line 1,978: | ||
=={{header|NewLISP}}== |
=={{header|NewLISP}}== |
||
< |
<syntaxhighlight lang="newlisp">(setq a '(1 2 3 4 5)) |
||
(apply + a) |
(apply + a) |
||
(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|Nim}}== |
=={{header|Nim}}== |
||
< |
<syntaxhighlight lang="nim">var xs = [1, 2, 3, 4, 5, 6] |
||
var sum, product: int |
var sum, product: int |
||
Line 2,006: | Line 2,006: | ||
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 = [1, 2, 3, 4, 5, 6] |
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: |
Or using a math function: |
||
< |
<syntaxhighlight lang="nim">import math |
||
let numbers = [1, 5, 4] |
let numbers = [1, 5, 4] |
||
Line 2,024: | Line 2,024: | ||
var product = 1 |
var product = 1 |
||
for n in numbers: |
for n in numbers: |
||
product *= n</ |
product *= n</syntaxhighlight> |
||
=={{header|Objeck}}== |
=={{header|Objeck}}== |
||
< |
<syntaxhighlight lang="objeck"> |
||
sum := 0; |
sum := 0; |
||
prod := 1; |
prod := 1; |
||
Line 2,035: | Line 2,035: | ||
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 2,052: | Line 2,052: | ||
return suml; |
return suml; |
||
}</ |
}</syntaxhighlight> |
||
Product: |
Product: |
||
< |
<syntaxhighlight lang="objc">- (float) prod:(NSMutableArray *)array |
||
{ |
{ |
||
int i, prod, value; |
int i, prod, value; |
||
Line 2,066: | Line 2,066: | ||
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 2,077: | Line 2,077: | ||
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 2,086: | Line 2,086: | ||
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}}== |
=={{header|Oforth}}== |
||
< |
<syntaxhighlight lang="oforth">[1, 2, 3, 4, 5 ] sum println |
||
[1, 3, 5, 7, 9 ] prod println</ |
[1, 3, 5, 7, 9 ] prod println</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,106: | Line 2,106: | ||
=={{header|Ol}}== |
=={{header|Ol}}== |
||
< |
<syntaxhighlight lang="scheme"> |
||
(print (fold + 0 '(1 2 3 4 5))) |
(print (fold + 0 '(1 2 3 4 5))) |
||
(print (fold * 1 '(1 2 3 4 5))) |
(print (fold * 1 '(1 2 3 4 5))) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|ooRexx}}== |
=={{header|ooRexx}}== |
||
{{trans|REXX}} |
{{trans|REXX}} |
||
< |
<syntaxhighlight lang="oorexx">a=.my_array~new(20) |
||
do i=1 To 20 |
do i=1 To 20 |
||
a[i]=i |
a[i]=i |
||
Line 2,134: | Line 2,134: | ||
prod*=self[i] |
prod*=self[i] |
||
End |
End |
||
Return prod</ |
Return prod</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20 |
<pre>1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20 |
||
Line 2,142: | Line 2,142: | ||
=={{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 2,148: | Line 2,148: | ||
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 2,162: | Line 2,162: | ||
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: |
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: |
||
< |
<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+}} |
{{works with|PARI/GP|2.10.0+}} |
||
Line 2,180: | Line 2,180: | ||
=={{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: |
Or using the [https://metacpan.org/pod/List::Util List::Util] module: |
||
< |
<syntaxhighlight lang="perl">use List::Util qw/sum0 product/; |
||
my @list = (1..9); |
my @list = (1..9); |
||
say "Sum: ", sum0(@list); # sum0 returns 0 for an empty list |
say "Sum: ", sum0(@list); # sum0 returns 0 for an empty list |
||
say "Product: ", product(@list);</ |
say "Product: ", product(@list);</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>Sum: 45 |
<pre>Sum: 45 |
||
Line 2,197: | Line 2,197: | ||
=={{header|Phix}}== |
=={{header|Phix}}== |
||
{{libheader|Phix/basics}} |
{{libheader|Phix/basics}} |
||
<!--< |
<!--<syntaxhighlight lang="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: #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;">"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> |
<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}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,209: | Line 2,209: | ||
=={{header|Phixmonti}}== |
=={{header|Phixmonti}}== |
||
< |
<syntaxhighlight lang="phixmonti">include ..\Utilitys.pmt |
||
( 1 2 3 4 5 ) |
( 1 2 3 4 5 ) |
||
Line 2,221: | Line 2,221: | ||
drop |
drop |
||
"mult is " print print nl</ |
"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}}== |
=={{header|Picat}}== |
||
< |
<syntaxhighlight lang="picat">go => |
||
L = 1..10, |
L = 1..10, |
||
println(sum=sum(L)), |
println(sum=sum(L)), |
||
Line 2,260: | Line 2,260: | ||
Prod=Prod0. |
Prod=Prod0. |
||
prod_rec([H|T], Prod0,Prod) => |
prod_rec([H|T], Prod0,Prod) => |
||
prod_rec(T, H*Prod0,Prod).</ |
prod_rec(T, H*Prod0,Prod).</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,279: | Line 2,279: | ||
=={{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}} |
{{Out}} |
||
<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}}== |
=={{header|Plain English}}== |
||
< |
<syntaxhighlight lang="plainenglish">An element is a thing with a number. |
||
To find a sum and a product of some elements: |
To find a sum and a product of some elements: |
||
Line 2,326: | Line 2,326: | ||
Shut down. |
Shut down. |
||
A sum is a number.</ |
A sum is a number.</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,335: | Line 2,335: | ||
=={{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}}== |
=={{header|PostScript}}== |
||
<lang> |
<syntaxhighlight lang="text"> |
||
/sumandproduct |
/sumandproduct |
||
{ |
{ |
||
Line 2,367: | Line 2,367: | ||
prod == |
prod == |
||
}def |
}def |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{libheader|initlib}} |
{{libheader|initlib}} |
||
< |
<syntaxhighlight lang="postscript"> |
||
% sum |
% sum |
||
[1 1 1 1 1] 0 {add} fold |
[1 1 1 1 1] 0 {add} fold |
||
Line 2,376: | Line 2,376: | ||
[1 1 1 1 1] 1 {mul} fold |
[1 1 1 1 1] 1 {mul} fold |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{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 2,394: | Line 2,394: | ||
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 2,404: | Line 2,404: | ||
$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 2,421: | Line 2,421: | ||
$ret | Add-Member NoteProperty Product $prod |
$ret | Add-Member NoteProperty Product $prod |
||
return $ret |
return $ret |
||
}</ |
}</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
<pre>PS> Get-SumAndProduct 5,9,7,2,3,8,4 |
<pre>PS> Get-SumAndProduct 5,9,7,2,3,8,4 |
||
Line 2,430: | Line 2,430: | ||
=={{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 2,443: | Line 2,443: | ||
Using fold |
Using fold |
||
< |
<syntaxhighlight lang="prolog"> |
||
add(A,B,R):- |
add(A,B,R):- |
||
R is A + B. |
R is A + B. |
||
Line 2,467: | Line 2,467: | ||
Prod = 24 . |
Prod = 24 . |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|PureBasic}}== |
=={{header|PureBasic}}== |
||
< |
<syntaxhighlight lang="purebasic">Dim MyArray(9) |
||
Define a, sum=0, prod=1 |
Define a, sum=0, prod=1 |
||
Line 2,483: | Line 2,483: | ||
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|NumPy}} |
{{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> |
||
Line 2,516: | Line 2,516: | ||
{{works with|QuickBasic}} |
{{works with|QuickBasic}} |
||
{{works with|True BASIC}} |
{{works with|True BASIC}} |
||
< |
<syntaxhighlight lang="qbasic">DIM array(1 TO 5) |
||
DATA 1, 2, 3, 4, 5 |
DATA 1, 2, 3, 4, 5 |
||
FOR index = LBOUND(array) TO UBOUND(array) |
FOR index = LBOUND(array) TO UBOUND(array) |
||
Line 2,530: | Line 2,530: | ||
PRINT "The sum is "; sum |
PRINT "The sum is "; sum |
||
PRINT "and the product is "; prod |
PRINT "and the product is "; prod |
||
END</ |
END</syntaxhighlight> |
||
=={{header|Quackery}}== |
=={{header|Quackery}}== |
||
< |
<syntaxhighlight lang="quackery">[ 0 swap witheach + ] is sum ( [ --> n ) |
||
[ 1 swap witheach * ] is product ( [ --> n )</ |
[ 1 swap witheach * ] is product ( [ --> n )</syntaxhighlight> |
||
In the shell (i.e. Quackery REPL): |
In the shell (i.e. Quackery REPL): |
||
<syntaxhighlight lang="quackery"> |
|||
<lang Quackery> |
|||
/O> ' [ 1 2 3 4 5 ] sum echo cr |
/O> ' [ 1 2 3 4 5 ] sum echo cr |
||
... ' [ 1 2 3 4 5 ] product echo |
... ' [ 1 2 3 4 5 ] product echo |
||
Line 2,544: | Line 2,544: | ||
15 |
15 |
||
120 |
120 |
||
Stack empty.</ |
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 |
||
(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> |
||
=={{header|Raku}}== |
=={{header|Raku}}== |
||
(formerly Perl 6) |
(formerly Perl 6) |
||
<lang |
<syntaxhighlight lang="raku" line>my @ary = 1, 5, 10, 100; |
||
say 'Sum: ', [+] @ary; |
say 'Sum: ', [+] @ary; |
||
say 'Product: ', [*] @ary;</ |
say 'Product: ', [*] @ary;</syntaxhighlight> |
||
=={{header|Rapira}}== |
=={{header|Rapira}}== |
||
< |
<syntaxhighlight lang="rapira">fun sumOfArr(arr) |
||
sum := 0 |
sum := 0 |
||
for N from 1 to #arr do |
for N from 1 to #arr do |
||
Line 2,577: | Line 2,577: | ||
od |
od |
||
return product |
return product |
||
end</ |
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" |
||
URL: http://rosettacode.org/wiki/Sum_and_product_of_array |
URL: http://rosettacode.org/wiki/Sum_and_product_of_array |
||
Line 2,618: | Line 2,618: | ||
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> |
||
{{Out}} |
{{Out}} |
||
Line 2,630: | Line 2,630: | ||
=={{header|Red}}== |
=={{header|Red}}== |
||
< |
<syntaxhighlight lang="rebol">Red [ |
||
red-version: 0.6.4 |
red-version: 0.6.4 |
||
description: "Find the sum and product of an array of numbers." |
description: "Find the sum and product of an array of numbers." |
||
Line 2,647: | Line 2,647: | ||
print a |
print a |
||
print ["Sum:" sum a] |
print ["Sum:" sum a] |
||
print ["Product:" product a]</ |
print ["Product:" product a]</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,656: | Line 2,656: | ||
=={{header|REXX}}== |
=={{header|REXX}}== |
||
< |
<syntaxhighlight lang="rexx">/*REXX program adds and multiplies N elements of a (populated) array @. */ |
||
numeric digits 200 /*200 decimal digit #s (default is 9).*/ |
numeric digits 200 /*200 decimal digit #s (default is 9).*/ |
||
parse arg N .; if N=='' then N=20 /*Not specified? Then use the default.*/ |
parse arg N .; if N=='' then N=20 /*Not specified? Then use the default.*/ |
||
Line 2,672: | Line 2,672: | ||
say ' sum of ' m " elements for the @ array is: " sum |
say ' sum of ' m " elements for the @ array is: " sum |
||
say ' product of ' m " elements for the @ array is: " prod |
say ' product of ' m " elements for the @ array is: " prod |
||
/*stick a fork in it, we're all done. */</ |
/*stick a fork in it, we're all done. */</syntaxhighlight> |
||
'''output''' using the default input of: <tt> 20 </tt> |
'''output''' using the default input of: <tt> 20 </tt> |
||
<pre> |
<pre> |
||
Line 2,680: | Line 2,680: | ||
=={{header|Ring}}== |
=={{header|Ring}}== |
||
< |
<syntaxhighlight lang="ring"> |
||
aList = 1:10 nSum=0 nProduct=0 |
aList = 1:10 nSum=0 nProduct=0 |
||
for x in aList nSum += x nProduct *= x next |
for x in aList nSum += x nProduct *= x next |
||
See "Sum = " + nSum + nl |
See "Sum = " + nSum + nl |
||
See "Product = " + nProduct + nl |
See "Product = " + nProduct + nl |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{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 2,702: | Line 2,702: | ||
# 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. |
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(0, :+) #=> 0 |
||
p arr.inject(1, :*) #=> 1 |
p arr.inject(1, :*) #=> 1 |
||
p arr.inject(:+) #=> nil |
p arr.inject(:+) #=> nil |
||
p arr.inject(:*) #=> nil</ |
p arr.inject(:*) #=> nil</syntaxhighlight> |
||
Enumerable#reduce is the alias of Enumerable#inject. |
Enumerable#reduce is the alias of Enumerable#inject. |
||
{{works with|Ruby|1.9.3}} |
{{works with|Ruby|1.9.3}} |
||
< |
<syntaxhighlight lang="ruby">arr = [1,2,3,4,5] |
||
p sum = arr.sum #=> 15 |
p sum = arr.sum #=> 15 |
||
p [].sum #=> 0</ |
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 2,731: | Line 2,731: | ||
Print " Sum is ";sum |
Print " Sum is ";sum |
||
Print "Product is ";product</ |
Print "Product is ";product</syntaxhighlight> |
||
=={{header|Rust}}== |
=={{header|Rust}}== |
||
< |
<syntaxhighlight lang="rust"> |
||
fn main() { |
fn main() { |
||
Line 2,749: | Line 2,749: | ||
println!("the sum is {} and the product is {}", sum, product); |
println!("the sum is {} and the product is {}", sum, product); |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|S-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. |
The sum of array elements is handled by an intrinsic. |
||
[note: print is slsh-specific; if not available, use printf().] |
[note: print is slsh-specific; if not available, use printf().] |
||
<lang |
<syntaxhighlight lang="s-lang">print(sum(a));</syntaxhighlight> |
||
The product is slightly more involved; I'll use this as a |
The product is slightly more involved; I'll use this as a |
||
chance to show the alternate stack-based use of 'foreach': |
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. |
% Skipping the loop variable causes the val to be placed on the stack. |
||
Line 2,770: | Line 2,770: | ||
prod *= (); |
prod *= (); |
||
print(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 2,780: | Line 2,780: | ||
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 2,792: | Line 2,792: | ||
#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 2,815: | Line 2,815: | ||
(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 2,838: | Line 2,838: | ||
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 2,844: | Line 2,844: | ||
=={{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> |
||
Line 2,851: | Line 2,851: | ||
=={{header|Sidef}}== |
=={{header|Sidef}}== |
||
Using built-in methods: |
Using built-in methods: |
||
< |
<syntaxhighlight lang="ruby">var ary = [1, 2, 3, 4, 5]; |
||
say ary.sum; # => 15 |
say ary.sum; # => 15 |
||
say ary.prod; # => 120</ |
say ary.prod; # => 120</syntaxhighlight> |
||
Alternatively, using hyper-operators: |
Alternatively, using hyper-operators: |
||
< |
<syntaxhighlight lang="ruby">var ary = [1, 2, 3, 4, 5]; |
||
say ary«+»; # => 15 |
say ary«+»; # => 15 |
||
say ary«*»; # => 120</ |
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 2,887: | Line 2,887: | ||
out output = "Sum: " sum |
out output = "Sum: " sum |
||
output = "Prod: " product |
output = "Prod: " product |
||
end</ |
end</syntaxhighlight> |
||
Input |
Input |
||
Line 2,902: | Line 2,902: | ||
=={{header|Sparkling}}== |
=={{header|Sparkling}}== |
||
< |
<syntaxhighlight lang="sparkling">spn:1> reduce({ 1, 2, 3, 4, 5 }, 0, function(x, y) { return x + y; }) |
||
= 15 |
= 15 |
||
spn:2> reduce({ 1, 2, 3, 4, 5 }, 1, function(x, y) { return x * y; }) |
spn:2> reduce({ 1, 2, 3, 4, 5 }, 1, function(x, y) { return x * y; }) |
||
= 120</ |
= 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 2,916: | Line 2,916: | ||
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 2,925: | Line 2,925: | ||
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}}== |
=={{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: |
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) |
sum(a) |
||
-3 |
-3 |
||
(-1)^mod(sum(a:<0),2)*exp(sum(log(abs(a)))) |
(-1)^mod(sum(a:<0),2)*exp(sum(log(abs(a)))) |
||
-120</ |
-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 <code>sum()</code> and <code>prod()</code>. |
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} |
{1 2 3 4 5 6 7 8 9 10} |
||
sum(L₁) |
sum(L₁) |
||
55 |
55 |
||
prod(L₁) |
prod(L₁) |
||
3628800</ |
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 2,974: | Line 2,974: | ||
( 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}}== |
=={{header|True BASIC}}== |
||
{{works with|QBasic}} |
{{works with|QBasic}} |
||
< |
<syntaxhighlight lang="qbasic">DIM array(1 TO 5) |
||
DATA 1, 2, 3, 4, 5 |
DATA 1, 2, 3, 4, 5 |
||
FOR index = LBOUND(array) TO UBOUND(array) |
FOR index = LBOUND(array) TO UBOUND(array) |
||
Line 2,997: | Line 2,997: | ||
PRINT "The sum is "; sum |
PRINT "The sum is "; sum |
||
PRINT "and the product is "; prod |
PRINT "and the product is "; prod |
||
END</ |
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 3,012: | Line 3,012: | ||
ENDLOOP |
ENDLOOP |
||
PRINT "product: ",product |
PRINT "product: ",product |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{Out}} |
{{Out}} |
||
<pre> |
<pre> |
||
Line 3,023: | Line 3,023: | ||
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 3,029: | Line 3,029: | ||
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|Bourne Again SHell}} |
{{works with|Bourne Again SHell}} |
||
Line 3,054: | Line 3,054: | ||
Using an actual array variable: |
Using an actual array variable: |
||
< |
<syntaxhighlight lang="bash">list=(20 20 2); |
||
(( sum=0, prod=1 )) |
(( sum=0, prod=1 )) |
||
for n in "${list[@]}"; do |
for n in "${list[@]}"; do |
||
Line 3,060: | Line 3,060: | ||
done |
done |
||
printf '%d\t%d\n' "$sum" "$prod" |
printf '%d\t%d\n' "$sum" "$prod" |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{Out}} |
{{Out}} |
||
Line 3,068: | Line 3,068: | ||
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 3,082: | Line 3,082: | ||
(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. |
||
Line 3,088: | Line 3,088: | ||
=={{header|Ursa}}== |
=={{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. |
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 |
append 34 76 233 8 2 734 56 stream |
||
Line 3,095: | Line 3,095: | ||
# outputs 3.95961079808E11 |
# outputs 3.95961079808E11 |
||
out (* stream) endl console</ |
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> |
||
{{Out}} |
{{Out}} |
||
Line 3,109: | Line 3,109: | ||
=={{header|V}}== |
=={{header|V}}== |
||
< |
<syntaxhighlight lang="v">[sp dup 0 [+] fold 'product=' put puts 1 [*] fold 'sum=' put puts].</syntaxhighlight> |
||
{{Out|Using it}} |
{{Out|Using it}} |
||
< |
<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() { |
||
int sum = 0, prod = 1; |
int sum = 0, prod = 1; |
||
int[] data = { 1, 2, 3, 4 }; |
int[] data = { 1, 2, 3, 4 }; |
||
Line 3,126: | Line 3,126: | ||
} |
} |
||
print(@"sum: $(sum)\nproduct: $(prod)"); |
print(@"sum: $(sum)\nproduct: $(prod)"); |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>sum: 10 |
<pre>sum: 10 |
||
Line 3,133: | Line 3,133: | ||
=={{header|VBA}}== |
=={{header|VBA}}== |
||
Assumes Excel is used. |
Assumes Excel is used. |
||
< |
<syntaxhighlight lang="vb">Sub Demo() |
||
Dim arr |
Dim arr |
||
arr = Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) |
arr = Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) |
||
Debug.Print "sum : " & Application.WorksheetFunction.Sum(arr) |
Debug.Print "sum : " & Application.WorksheetFunction.Sum(arr) |
||
Debug.Print "product : " & Application.WorksheetFunction.Product(arr) |
Debug.Print "product : " & Application.WorksheetFunction.Product(arr) |
||
End Sub</ |
End Sub</syntaxhighlight>{{Out}} |
||
<pre>sum : 55 |
<pre>sum : 55 |
||
product : 3628800</pre> |
product : 3628800</pre> |
||
=={{header|VBScript}}== |
=={{header|VBScript}}== |
||
< |
<syntaxhighlight lang="vb">Function sum_and_product(arr) |
||
sum = 0 |
sum = 0 |
||
product = 1 |
product = 1 |
||
Line 3,158: | Line 3,158: | ||
myarray = Array(1,2,3,4,5,6) |
myarray = Array(1,2,3,4,5,6) |
||
sum_and_product(myarray) |
sum_and_product(myarray) |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{Out}} |
{{Out}} |
||
Line 3,169: | Line 3,169: | ||
{{trans|C#}} |
{{trans|C#}} |
||
< |
<syntaxhighlight lang="vbnet">Module Program |
||
Sub Main() |
Sub Main() |
||
Dim arg As Integer() = {1, 2, 3, 4, 5} |
Dim arg As Integer() = {1, 2, 3, 4, 5} |
||
Line 3,175: | Line 3,175: | ||
Dim prod = arg.Aggregate(Function(runningProduct, nextFactor) runningProduct * nextFactor) |
Dim prod = arg.Aggregate(Function(runningProduct, nextFactor) runningProduct * nextFactor) |
||
End Sub |
End Sub |
||
End Module</ |
End Module</syntaxhighlight> |
||
=={{header|Wart}}== |
=={{header|Wart}}== |
||
< |
<syntaxhighlight lang="wart">def (sum_prod nums) |
||
(list (+ @nums) (* @nums))</ |
(list (+ @nums) (* @nums))</syntaxhighlight> |
||
=={{header|WDTE}}== |
=={{header|WDTE}}== |
||
< |
<syntaxhighlight lang="wdte">let a => import 'arrays'; |
||
let s => import 'stream'; |
let s => import 'stream'; |
||
let sum array => a.stream array -> s.reduce 0 +; |
let sum array => a.stream array -> s.reduce 0 +; |
||
let prod array => a.stream prod -> s.reduce 1 *;</ |
let prod array => a.stream prod -> s.reduce 1 *;</syntaxhighlight> |
||
=={{header|Wortel}}== |
=={{header|Wortel}}== |
||
< |
<syntaxhighlight lang="wortel">@sum [1 2 3 4] ; returns 10 |
||
@prod [1 2 3 4] ; returns 24</ |
@prod [1 2 3 4] ; returns 24</syntaxhighlight> |
||
=={{header|Wren}}== |
=={{header|Wren}}== |
||
{{libheader|Wren-math}} |
{{libheader|Wren-math}} |
||
< |
<syntaxhighlight lang="ecmascript">import "/math" for Nums |
||
var a = [7, 10, 2, 4, 6, 1, 8, 3, 9, 5] |
var a = [7, 10, 2, 4, 6, 1, 8, 3, 9, 5] |
||
System.print("Array : %(a)") |
System.print("Array : %(a)") |
||
System.print("Sum : %(Nums.sum(a))") |
System.print("Sum : %(Nums.sum(a))") |
||
System.print("Product : %(Nums.prod(a))")</ |
System.print("Product : %(Nums.prod(a))")</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 3,208: | Line 3,208: | ||
=={{header|XPL0}}== |
=={{header|XPL0}}== |
||
< |
<syntaxhighlight lang="xpl0">code CrLf=9, IntOut=11; |
||
func SumProd(A, L); |
func SumProd(A, L); |
||
Line 3,219: | Line 3,219: | ||
]; \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}} |
{{Out}} |
||
Line 3,230: | Line 3,230: | ||
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 3,265: | Line 3,265: | ||
</xsl:call-template> |
</xsl:call-template> |
||
</xsl:template> |
</xsl:template> |
||
</xsl:stylesheet></ |
</xsl:stylesheet></syntaxhighlight> |
||
=={{header|Yabasic}}== |
=={{header|Yabasic}}== |
||
{{trans|QBasic}} |
{{trans|QBasic}} |
||
< |
<syntaxhighlight lang="yabasic">dim array(5) |
||
data 1, 2, 3, 4, 5 |
data 1, 2, 3, 4, 5 |
||
for index = 1 to arraysize(array(), 1) |
for index = 1 to arraysize(array(), 1) |
||
Line 3,284: | Line 3,284: | ||
print "The sum is ", sum //15 |
print "The sum is ", sum //15 |
||
print "and the product is ", prod //120 |
print "and the product is ", prod //120 |
||
end</ |
end</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 |
||
Line 3,297: | Line 3,297: | ||
=={{header|Zoea}}== |
=={{header|Zoea}}== |
||
<syntaxhighlight lang="zoea"> |
|||
<lang Zoea> |
|||
program: sum_and_product |
program: sum_and_product |
||
case: 1 |
case: 1 |
||
Line 3,305: | Line 3,305: | ||
input: [2,3,4] |
input: [2,3,4] |
||
output: [9,24] |
output: [9,24] |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Zoea Visual}}== |
=={{header|Zoea Visual}}== |