Anonymous user
Sum and product of an array: Difference between revisions
m
Highlighting, whitespace
(rm what seems a duplicate, even if a little bit different in syntax (Standard ML twice)) |
m (Highlighting, whitespace) |
||
Line 1:
{{task|Arithmetic operations}}[[Category:Iteration]]
Compute the sum and product of an array of integers.
=={{header|4D}}==
$sum:=0
$product:=1
For ($i;1;Size of array($list))
$sum:=$var+$list{$i}
$product:=$product*$list{$i}
End for</lang>
=={{header|ActionScript}}==
<lang actionscript>package {
import flash.display.Sprite;
Line 38 ⟶ 35:
}
}
}</lang>
=={{header|Ada}}==
<lang ada>type Int_Array is array(Integer range <>) of Integer;
Define the product function
<lang ada>function Product(Item : Int_Array) return Integer is
begin
for I in Item'range loop
Prod := Prod * Item(I);
end loop;
return
end Product;</lang>
This function will raise the predefined exception Constraint_Error if the product overflows the values represented by type Integer
=={{header|ALGOL 68}}==
)</lang>
Output:
Sum: 55, Product:3628800;
Line 101 ⟶ 92:
prod list
120
=={{header|AppleScript}}==
=={{header|AutoHotkey}}==
<lang AutoHotkey>numbers = 1,2,3,4,5
product := 1
loop, parse, numbers, `,
Line 119 ⟶ 108:
product *= A_LoopField
}
msgbox, sum = %sum%`nproduct = %product%</lang>
=={{header|AWK}}==
For array input, it is easiest to "deserialize" it from a string with the split() function.
<lang awk>$ awk 'func sum(s){split(s,a);r=0;for(i in a)r+=a[i];return r}{print sum($0)}'
1 2 3 4 5 6 7 8 9 10
55
Line 131 ⟶ 117:
$ awk 'func prod(s){split(s,a);r=1;for(i in a)r*=a[i];return r}{print prod($0)}'
1 2 3 4 5 6 7 8 9 10
3628800</lang>
=={{header|BASIC}}==
{{works with|QuickBasic|4.5}}
<lang
{{works with|FreeBASIC}}
<lang
dim sum as integer = 0
dim prod as integer = 1
for index as integer = lbound(array) to ubound(array)
sum += array(index)
prod *= array(index)
next</lang>
=={{header|C}}==
<lang
for (p = arg; p!=end; ++p) {
sum += *p;
prod *= *p;
}</lang>
=={{header|C++}}==
{{libheader|STL}}
<lang
int arg[] = { 1, 2, 3, 4, 5 };
int sum = std::accumulate(arg, arg+5, 0, std::plus<int>());
// or just
// std::accumulate(arg, arg + 5, 0);
// since plus() is the default functor for accumulate
int prod = std::accumulate(arg, arg+5, 1, std::multiplies<int>());</lang>
Template alternative:
<lang cpp>// this would be more elegant using STL collections
template <typename T> T sum (const T *array, const unsigned n)
{
T accum = 0;
for (unsigned i=0; i<n; i++)
accum += array[i];
return accum;
}
template <typename T> T prod (const T *array, const unsigned n)
{
T accum = 1;
for (unsigned i=0; i<n; i++)
accum *= array[i];
return accum;
}
#include <iostream>
using std::cout;
using std::endl;
int main ()
{
int aint[] = {1, 2, 3};
cout << sum(aint,3) << " " << prod(aint, 3) << endl;
float aflo[] = {1.1, 2.02, 3.003, 4.0004};
cout << sum(aflo,4) << " " << prod(aflo,4) << endl;
return 0;
}</lang>
=={{header|C sharp|C#}}==
<lang csharp>int sum = 0, prod = 1;
Line 225 ⟶ 203:
=={{header|Clean}}==
=={{header|ColdFusion}}==
Sum of an Array,
<cfset Variables.myArray = [1,2,3,4,5,6,7,8,9,10]>
<cfoutput>#ArraySum(Variables.myArray)#</cfoutput>
Line 243 ⟶ 218:
</cfloop>
<cfoutput>#Variables.Product#</cfoutput>
=={{header|Common Lisp}}==
<lang lisp>(let ((data #(1 2 3 4 5))) ; the array
(values (reduce #'+ data) ; sum
(reduce #'* data))) ; product</lang>
=={{header|D}}==
<lang d>auto sum = 0, prod = 1;
Line 263 ⟶ 235:
writefln("Product: ", r._1);
</lang>
=={{header|Delphi}}==
<lang
end;
end;</lang>
=={{header|E}}==
=={{header|Emacs Lisp}}==
{{works with|XEmacs|version 21.5.21}}
Line 290 ⟶ 259:
=={{header|Erlang}}==
Using the standard libraries:
<lang erlang>% create the list:
L = lists:seq(1, 10).
% and compute its sum:
P = lists:foldl(fun (X, P) -> X * P end, 1, L).</lang>
Or defining our own versions:
<lang erlang>-module(list_sum).
-export([sum_rec/1, sum_tail/1]).
% recursive definition:
sum_rec([]) ->
0;
sum_rec([Head|Tail]) ->
% tail-recursive definition:
sum_tail(L) ->
sum_tail(L, 0).
sum_tail([], Acc) ->
Acc;
sum_tail([Head|Tail], Acc) ->
sum_tail(Tail, Head + Acc).</lang>
=={{header|Factor}}==
1 5 1 <range> [ sum . ] [ product . ] bi
Line 338 ⟶ 303:
=={{header|Fortran}}==
In ISO Fortran 90 and later, use SUM and PRODUCT intrinsics:
<lang
=={{header|Groovy}}==
Groovy adds a "sum()" method for collections, but not a "product()" method:
<lang groovy>[1,2,3,4,5].sum()</lang>
However, for general purpose "reduction" or "folding" operations, Groovy does provide an "inject()" method for collections similar to "inject" in Ruby.
<lang groovy>[1,2,3,4,5].inject(0) { sum, val -> sum + val }
=={{header|Haskell}}==
For lists, ''sum'' and ''product'' are already defined in the Prelude:
<lang haskell>values = [1..10]
s = sum values
p = product values
s' = foldl (+) 0 values -- the hard way
p' = foldl (*) 1 values</lang>
To do the same for an array, just convert it lazily to a list:
<lang haskell>import Data.Array
values = listArray (1,10) [1..10]
s = sum . elems $ values
p = product . elems $ values</lang>
=={{header|IDL}}==
array = [3,6,8]
Line 412 ⟶ 366:
=={{header|Java}}==
{{works with|Java|1.5+}}
<lang
public static void main(String[] args){
int sum= 0;
Line 425 ⟶ 379:
=={{header|JavaScript}}==
=={{header|Logo}}==
=={{header|Lucid}}==
prints a running sum and product of sequence 1,2,3...
=={{header|Mathematica}}==
Mathematica provides many ways of doing the sum of an array (any kind of numbers or symbols):
<lang Mathematica>a = {1, 2, 3, 4, 5}
Plus @@ a
Total[a]
a // Total
Sum[a[[i]], {i, 1, Length[a]}]
all give 15. For product we also have a couple of choices:
<lang Mathematica>a = {1, 2, 3, 4, 5}
Times @@ a
Product[a[[i]], {i, 1, Length[a]}]
all give 120.
=={{header|MAXScript}}==
=={{header|Nial}}==
Nial being an array language, what applies to individual elements are extended to cover array operations by default strand notation
<lang nial>+ 1 2 3
= 6
* 1 2 3
= 6</lang>
array notation
grouped notation
(All these notations are equivalent)
=={{header|Modula-3}}==
<lang modula3>MODULE Sumprod EXPORTS Main;
FROM IO IMPORT Put;
Line 510 ⟶ 451:
Put("Sum of array: " & Int(sum) & "\n");
Put("Product of array: " & Int(prod) & "\n");
END Sumprod.</lang>
Output:
<pre>Sum of array: 15
=={{header|Objective-C}}==
{{works with|GCC|4.0.1 (apple)}}
Sum:
}</lang>
Product:
}</lang>
=={{header|OCaml}}==
===Lists===
<lang ocaml>(* ints *)
let x = [1; 2; 3; 4; 5];;
List.fold_left (+) 0 x;;
(* floats *)
let x = [1; 2; 3; 4; 5];;
List.fold_left (+.) 0.0 x;;
=={{header|Octave}}==
<lang octave>a = [ 1, 2, 3, 4, 5, 6 ];
b = [ 10, 20, 30, 40, 50, 60 ];
vsum = a + b;
vprod = a .* b;</lang>
=={{header|Oz}}==
<lang oz>functor
import
Application System
Line 595 ⟶ 523:
{Application.exit 0}
end</lang>
=={{header|Perl}}==
Alternate:
{{libheader|List::Util}}
my @list = (1, 2, 3);
my $sum1 = sum 0, @list; # 0 identity to allow empty list
my $sum2 = reduce { $a + $b } 0, @list;
my $product = reduce { $a * $b } 1, @list;</lang>
Alternate
'''# TMTOWTDI'''
=={{header|PHP}}==
<lang
=={{header|Pop11}}==
Simple loop:
<lang pop11>lvars i, sum = 0, prod = 1, ar = {1 2 3 4 5 6 7 8 9};
for i from 1 to length(ar) do
ar(i) + sum -> sum;
endfor;</lang>
One can alternativly use second order iterator:
<lanf pop11>lvars sum = 0, prod = 1, ar = {1 2 3 4 5 6 7 8 9};
appdata(ar, procedure(x); x + sum -> sum; endprocedure);
=={{header|PowerShell}}==
The <code>Measure-Object</code> cmdlet already knows how to compute a sum:
Line 693 ⟶ 610:
=={{header|Prolog}}==
test
Line 706 ⟶ 623:
=={{header|Python}}==
{{works with|Python|2.5}}
product = 1
for i in numbers:
product *= i</lang>
Or functionally (faster but perhaps less clear):
{{works with|Python|2.5}}
{{libheader|numpy}}
=={{header|R}}==
<lang
=={{header|Raven}}==
=={{header|Ruby}}==
<lang ruby>
{{works with|Ruby|1.9}}
<lang ruby>
=={{header|Scala}}==
It may also be done in a classic imperative way :
<lang
=={{header|Scheme}}==
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.
(reduce + 0 '(1 2 3 4 5)) ;; 0 is unit for +
(reduce * 1 '(1 2 3 4 5)) ;; 1 is unit for *</lang>
=={{header|Seed7}}==
const func integer: prodArray (in array integer: valueArray) is func
result
var integer: prod is 1;
local
var integer: value is 0;
begin
for value range valueArray do
prod *:= value;
end for;
end func;</lang>
Call these functions with:
writeln(sumArray([](1, 2, 3, 4, 5)));
writeln(prodArray([](1, 2, 3, 4, 5)));
Line 810 ⟶ 713:
=={{header|Slate}}==
<lang slate>#(1 2 3 4 5) reduce: [:sum :number | sum + number]
#(1 2 3 4 5) reduce: [:
Shorthand for the above with a macro:
<lang slate>#(1 2 3 4 5) reduce: #+ `er
#(1 2 3 4 5) reduce: #
=={{header|Smalltalk}}==
<lang smalltalk>
Some implementation also provide a ''fold:'' message:
<lang smalltalk>#(1 2 3 4 5) fold: [:sum :number | sum + number]
=={{header|Standard ML}}==
===Lists===
<lang ocaml(* ints *)
val x = [1, 2, 3, 4, 5];
foldl op+ 0 x;
(* reals *)
val x = [1.0, 2.0, 3.0, 4.0, 5.0];
foldl op+ 0.0 x;
=={{header|Tcl}}==
<lang tcl>set arr [list 3 6 8]
Line 860 ⟶ 753:
=={{header|Toka}}==
( product )
=={{header|UNIX Shell}}==
{{works with|NetBSD|3.0}}
Line 912 ⟶ 804:
done;
echo $SUM $PROD
=={{header|UnixPipes}}==
prod() {
|