Sum and product of an array: Difference between revisions

From Rosetta Code
Content added Content deleted
(Much improved D code)
Line 984: Line 984:
prod ==
prod ==
}def
}def
</lang>

{{libheader|initlib}}
<lang postscript>
% sum
[1 1 1 1 1] 0 {add} fold
% product
[1 1 1 1 1] 1 {mul} fold

</lang>
</lang>



Revision as of 07:02, 26 March 2011

Task
Sum and product of an array
You are encouraged to solve this task according to the task description, using any language you may know.

Compute the sum and product of an array of integers.

4D

<lang 4d>ARRAY INTEGER($list;0) For ($i;1;5)

      APPEND TO ARRAY($list;$i)

End for

$sum:=0 $product:=1 For ($i;1;Size of array($list))

  $sum:=$var+$list{$i}
  $product:=$product*$list{$i}

End for</lang>

ActionScript

<lang actionscript>package { import flash.display.Sprite;

public class SumAndProduct extends Sprite { public function SumAndProduct() { var arr:Array = [1, 2, 3, 4, 5]; var sum:int = 0; var prod:int = 1;

for (var i:int = 0; i < arr.length; i++) { sum += arr[i]; prod *= arr[i]; }

trace("Sum: " + sum); // 15 trace("Product: " + prod); // 120 } } }</lang>

Ada

<lang ada>type Int_Array is array(Integer range <>) of Integer;

array : Int_Array := (1,2,3,4,5,6,7,8,9,10); Sum : Integer := 0; for I in array'range loop

  Sum := Sum + array(I);

end loop;</lang> Define the product function <lang ada>function Product(Item : Int_Array) return Integer is

 Prod : Integer := 1;

begin

 for I in Item'range loop
    Prod := Prod * Item(I);
 end loop;
 return Prod;

end Product;</lang> This function will raise the predefined exception Constraint_Error if the product overflows the values represented by type Integer

ALGOL 68

<lang algol68>main:(

 INT default upb := 3;
 MODE INTARRAY = [default upb]INT;

 INTARRAY array = (1,2,3,4,5,6,7,8,9,10);
 INT sum := 0;
 FOR i FROM LWB array TO UPB array DO
    sum +:= array[i]
 OD;

 # Define the product function #
 PROC int product = (INTARRAY item)INT:
 (
   INT prod :=1;
   FOR i FROM LWB item TO UPB item DO
      prod *:= item[i]
   OD;
   prod
 ) # int product # ;
 printf(($" Sum: "g(0)$,sum,$", Product:"g(0)";"l$,int product(array)))

)</lang> Output:

Sum: 55, Product:3628800;

APL

Works with: APL2

<lang apl> sum ← +/

     prod ←  ×/
     
     list ←  1 2 3 4 5 
     
     sum  list

15

     prod list

120</lang>

AppleScript

<lang applescript>set array to {1, 2, 3, 4, 5} set sum to 0 set product to 1 repeat with i in array

   set sum to sum + i
   set product to product * i

end repeat</lang>

AutoHotkey

<lang AutoHotkey>numbers = 1,2,3,4,5 product := 1 loop, parse, numbers, `, { sum += A_LoopField product *= A_LoopField } msgbox, sum = %sum%`nproduct = %product%</lang>

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

$ 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>

BASIC

Works with: GW-BASIC
Works with: QBasic

<lang qbasic>10 REM Create an array with some test data in it 20 DIM A(5) 30 FOR I = 1 TO 5: READ A(I): NEXT I 40 DATA 1, 2, 3, 4, 5 50 REM Find the sum of elements in the array 60 S = 0 65 P = 1 70 FOR I = 1 TO 5 72 S = SUM + A(I) 75 P = P * A(I) 77 NEXT I 80 PRINT "The sum is "; S; 90 PRINT " and the product is "; P</lang>

Works with: FreeBASIC

<lang freebasic>dim array(5) as integer = { 1, 2, 3, 4, 5 }

dim sum as integer = 0 dim prod as integer = 1 for index as integer = lbound(array) to ubound(array)

 sum += array(index)
 prod *= array(index)

next</lang>

C

<lang c>/* using pointer arithmetic (because we can, I guess) */ int arg[] = { 1,2,3,4,5 }; int arg_length = sizeof(arg)/sizeof(arg[0]); int *end = arg+arg_length; int sum = 0, prod = 1; int *p;

for (p = arg; p!=end; ++p) {

  sum += *p;
  prod *= *p;

}</lang>

C++

Library: STL

<lang cpp>#include <numeric>

  1. include <functional>

int arg[] = { 1, 2, 3, 4, 5 }; int sum = std::accumulate(arg, arg+5, 0, std::plus<int>()); // or just // std::accumulate(arg, arg + 5, 0); // since plus() is the default functor for accumulate int prod = std::accumulate(arg, arg+5, 1, std::multiplies<int>());</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;

}

  1. 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>

C#

<lang csharp>int sum = 0, prod = 1; int[] arg = { 1, 2, 3, 4, 5 }; foreach (int value in arg) {

 sum += value;
 prod *= value;

}</lang>

Alternative using Linq (C# 3)

Works with: C# version 3

<lang csharp>int[] arg = { 1, 2, 3, 4, 5 }; int sum = arg.Sum(); int prod = arg.Aggregate((runningProduct, nextFactor) => runningProduct * nextFactor);</lang>

Clean

<lang clean>array = {1, 2, 3, 4, 5} Sum = sum [x \\ x <-: array] Prod = foldl (*) 1 [x \\ x <-: array]</lang>

Clojure

<lang lisp> (defn sum [vals] (reduce + vals))

(defn product [vals] (reduce * vals)) </lang>

ColdFusion

Sum of an Array, <lang cfm><cfset Variables.myArray = [1,2,3,4,5,6,7,8,9,10]> <cfoutput>#ArraySum(Variables.myArray)#</cfoutput></lang>

Product of an Array, <lang cfm><cfset Variables.myArray = [1,2,3,4,5,6,7,8,9,10]> <cfset Variables.Product = 1> <cfloop array="#Variables.myArray#" index="i">

<cfset Variables.Product *= i>

</cfloop> <cfoutput>#Variables.Product#</cfoutput></lang>

Common Lisp

<lang lisp>(let ((data #(1 2 3 4 5)))  ; the array

 (values (reduce #'+ data)       ; sum
         (reduce #'* data)))     ; product</lang>

D

<lang d>import std.stdio;

void main() {

   auto array = [1, 2, 3, 4, 5];
   int sum = 0;
   int prod = 1;
   foreach (x; array) {
       sum += x;
       prod *= x;
   }
   writeln("Sum: ", sum);
   writeln("Product: ", prod);

}</lang> Output:

Sum: 15
Product: 120

Compute sum and product of array in one pass using std.algorithm (same output): <lang d>import std.stdio, std.algorithm, std.typecons;

void main() {

   auto array = [1, 2, 3, 4, 5];
   // Results are stored in a tuple
   auto r = reduce!("a + b", "a * b")(tuple(0, 1), array);
   writeln("Sum: ", r[0]);
   writeln("Product: ", r[1]);

}</lang>

Delphi

<lang delphi>var

 Ints   : array[1..5] of integer = (1,2,3,4,5) ;
 i,Sum  : integer = 0 ;
 Prod   : integer = 1 ;

begin

 for i := 1 to length(ints) do begin
   inc(sum,ints[i]) ;
   prod := prod * ints[i]
 end;

end;</lang>

E

<lang e>pragma.enable("accumulator") accum 0 for x in [1,2,3,4,5] { _ + x } accum 1 for x in [1,2,3,4,5] { _ * x }</lang>

Emacs Lisp

Works with: XEmacs version version 21.5.21

<lang lisp>(setq array [1 2 3 4 5]) (eval (concatenate 'list '(+) array)) (eval (concatenate 'list '(*) array))</lang>

Erlang

Using the standard libraries: <lang erlang>% create the list: L = lists:seq(1, 10).

% and compute its sum: S = lists:sum(L). P = lists:foldl(fun (X, P) -> X * P end, 1, L).</lang> To compute sum and products in one pass: <lang erlang> {Prod,Sum} = lists:foldl(fun (X, {P,S}) -> {P*X,S+X} end, {1,0}, lists:seq(1,10)).</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]) ->

   Head + sum_rec(Tail).

% tail-recursive definition: sum_tail(L) ->

   sum_tail(L, 0).

sum_tail([], Acc) ->

   Acc;

sum_tail([Head|Tail], Acc) ->

   sum_tail(Tail, Head + Acc).</lang>

Euphoria

<lang euphoria>sequence array integer sum,prod

array = { 1, 2, 3, 4, 5 }

sum = 0 prod = 1 for i = 1 to length(array) do

 sum += array[i]
 prod *= array[i]

end for

printf(1,"sum is %d\n",sum) printf(1,"prod is %d\n",prod)</lang>

Output:

sum is 15
prod is 120

F#

<lang fsharp> let numbers = [| 1..10 |] let sum = numbers |> Array.sum let product = numbers |> Array.fold (*) 1 </lang>

Factor

<lang factor>1 5 1 <range> [ sum . ] [ product . ] bi

   15 120

{ 1 2 3 4 } [ sum ] [ product ] bi

   10 24</lang>

sum and product are defined in the sequences vocabulary: <lang factor>: sum ( seq -- n ) 0 [ + ] reduce ;

product ( seq -- n ) 1 [ * ] reduce ;</lang>

Fantom

<lang fantom> class Main {

 public static Void main ()
 {
   Int[] array := (1..20).toList
   
   // you can use a loop
   Int sum := 0
   array.each |Int n| { sum += n }
   echo ("Sum of array is : $sum")
   Int product := 1
   array.each |Int n| { product *= n }
   echo ("Product of array is : $product")
   // or use 'reduce'
   // 'reduce' takes a function, 
   //       the first argument is the accumulated value
   //       and the second is the next item in the list
   sum = array.reduce(0) |Obj r, Int v -> Obj| 
   { 
     return (Int)r + v 
   }
   echo ("Sum of array : $sum")
   product = array.reduce(1) |Obj r, Int v -> Obj| 
   { 
     return (Int)r * v 
   }
   echo ("Product of array : $product")
 }

} </lang>

Forth

<lang forth>: third ( a b c -- a b c a ) 2 pick ;

reduce ( xt n addr cnt -- n' ) \ where xt ( a b -- n )
 cells bounds do i @ third execute  cell +loop nip ;

create a 1 , 2 , 3 , 4 , 5 ,

' + 0 a 5 reduce . \ 15 ' * 1 a 5 reduce . \ 120</lang>

Fortran

In ISO Fortran 90 and later, use SUM and PRODUCT intrinsics: <lang fortran>integer, dimension(10) :: a = (/ (i, i=1, 10) /) integer :: sresult, presult

sresult = sum(a); presult = product(a);</lang>

Go

<lang go>package main

import "fmt"

func main() {

   sum, prod := 0, 1
   for _, x := range []int{1,2,5} {
       sum += x
       prod *= x
   }
   fmt.Println(sum, prod)

}</lang>

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 } [1,2,3,4,5].inject(1) { prod, val -> prod * val }</lang>

Haskell

For lists, sum and product are already defined in the Prelude: <lang haskell>values = [1..10]

s = sum values -- the easy way 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>

HicEst

<lang hicest>array = $ ! 1, 2, ..., LEN(array)

sum = SUM(array)

product = 1 ! no built-in product function in HicEst DO i = 1, LEN(array)

 product = product * array(i)

ENDDO

WRITE(ClipBoard, Name) n, sum, product ! n=100; sum=5050; product=9.33262154E157;</lang>

IDL

<lang idl>array = [3,6,8] print,total(array) print,product(array)</lang>

Icon and Unicon

The program below prints the sum and product of the arguments to the program. <lang Icon>procedure main(arglist) every ( sum := 0 ) +:= !arglist every ( prod := 1 ) *:= !arglist write("sum := ", sum,", prod := ",prod) end</lang>

Inform 7

<lang inform7>Sum And Product is a room.

To decide which number is the sum of (N - number) and (M - number) (this is summing): decide on N + M.

To decide which number is the product of (N - number) and (M - number) (this is production): decide on N * M.

When play begins: let L be {1, 2, 3, 4, 5}; say "List: [L in brace notation], sum = [summing reduction of L], product = [production reduction of L]."; end the story.</lang>

J

<lang j>sum =: +/ product =: */</lang>

For example:

<lang j> sum 1 3 5 7 9 11 13 49

  product 1 3 5 7 9 11 13

135135

  a=: 3 10 ?@$ 100  NB. random array
  a

90 47 58 29 22 32 55 5 55 73 58 50 40 5 69 46 34 40 46 84 29 8 75 97 24 40 21 82 77 9

  sum a

177 105 173 131 115 118 110 127 178 166

  product a

151380 18800 174000 14065 36432 58880 39270 16400 194810 55188

  sum"1 a

466 472 462

  product"1 a

5.53041e15 9.67411e15 1.93356e15</lang>

Java

Works with: Java version 1.5+

<lang java5>public class SumProd {

public static void main(final String[] args)
{
 int sum = 0;
 int prod = 1;
 int[] arg = {1,2,3,4,5};
 for (int i : arg)
 {
  sum += i;
  prod *= i;
 }
}

}</lang>

JavaScript

<lang javascript>var array = [1, 2, 3, 4, 5],

   sum = 0,
   prod = 1,
   i;

for (i = 0; i < array.length; i += 1) {

   sum += array[i];
   prod *= array[i];

} alert(sum + ' ' + prod);</lang>


Works with: Javascript version 1.8

Where supported, the reduce method can also be used: <lang javascript>var array = [1, 2, 3, 4, 5],

   sum = array.reduce(function (a, b) {
       return a + b;
   }, 0),
   prod = array.reduce(function (a, b) {
       return a * b;
   }, 1);

alert(sum + ' ' + prod);</lang>

Liberty BASIC

<lang lb>Dim array(19)

For i = 0 To 19

   array(i) = Int(Rnd(1) * 20)

Next i

'product must first equal one or you will get 0 as the product product = 1 For i = 0 To 19

   sum = (sum + array(i))
   product = (product * array(i))

next i

Print "Sum is " + str$(sum) Print "Product is " + str$(product)</lang>

<lang logo>print apply "sum arraytolist {1 2 3 4 5} print apply "product arraytolist {1 2 3 4 5}</lang>

Lua

<lang lua> function sumf(a, ...) return a and a + sumf(...) or 0 end function sumt(t) return sumf(unpack(t)) end function prodf(a, ...) return a and a * prodf(...) or 1 end function prodt(t) return prodf(unpack(t)) end

print(sumt{1, 2, 3, 4, 5}) print(prodt{1, 2, 3, 4, 5})</lang>

Lucid

prints a running sum and product of sequence 1,2,3... <lang lucid>[%sum,product%]

where
   x = 1 fby x + 1;
   sum = 0 fby sum + x;
   product = 1 fby product * x
end</lang>

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 Apply[Plus, a] Total[a] Total@a a // Total Sum[ai, {i, 1, Length[a]}] Sum[i, {i, a}]</lang> all give 15. For product we also have a couple of choices: <lang Mathematica>a = {1, 2, 3, 4, 5} Times @@ a Apply[Times, a] Product[ai, {i, 1, Length[a]}] Product[i, {i, a}]</lang> all give 120.

MATLAB

These two function are built into MATLAB as the "sum(array)" and "prod(array)" functions.

Sample Usage: <lang MATLAB>>> array = [1 2 3;4 5 6;7 8 9]

array =

    1     2     3
    4     5     6
    7     8     9

>> sum(array,1)

ans =

   12    15    18

>> sum(array,2)

ans =

    6
   15
   24

>> prod(array,1)

ans =

   28    80   162

>> prod(array,2)

ans =

    6
  120
  504</lang>

MAXScript

<lang maxscript>arr = #(1, 2, 3, 4, 5) sum = 0 for i in arr do sum += i product = 1 for i in arr do product *= i</lang>

MUMPS

<lang MUMPS> SUMPROD(A)

;Compute the sum and product of the numbers in the array A
NEW SUM,PROD,POS
;SUM is the running sum, 
;PROD is the running product,
;POS is the position within the array A
SET SUM=0,PROD=1,POS=""
FOR  SET POS=$ORDER(A(POS)) Q:POS=""  SET SUM=SUM+A(POS),PROD=PROD*A(POS)
WRITE !,"The sum of the array is "_SUM
WRITE !,"The product of the array is "_PROD
KILL SUM,PROD,POS
QUIT</lang>

Example:

USER>SET C(-1)=2,C("A")=3,C(42)=1,C(0)=7
 
USER>D SUMPROD^ROSETTA(.C)
 
The sum of the array is 13
The product of the array is 42

Note - the string "A" converts to 0 when doing mathematical operations.

USER>SET C(-1)=2,C("A")="3H",C(42)=.1,C(0)=7.0,C("B")="A"
 
USER>D SUMPROD^ROSETTA(.C)
 
The sum of the array is 12.1
The product of the array is 0

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 <lang nial>+ [1,2,3]</lang> grouped notation <lang nial>(* 1 2 3) = 6

  • (1 2 3)

= 6</lang> (All these notations are equivalent)

Modula-3

<lang modula3>MODULE Sumprod EXPORTS Main;

FROM IO IMPORT Put; FROM Fmt IMPORT Int;

VAR a := ARRAY [1..5] OF INTEGER {1, 2, 3, 4, 5}; VAR sum: INTEGER := 0; VAR prod: INTEGER := 1;

BEGIN

 FOR i := FIRST(a) TO LAST(a) DO
   INC(sum, a[i]);
   prod := prod * a[i];
 END;
 Put("Sum of array: " & Int(sum) & "\n");
 Put("Product of array: " & Int(prod) & "\n");

END Sumprod.</lang> Output:

Sum of array: 15
Product of array: 120

Objective-C

Works with: GCC version 4.0.1 (apple)

Sum: <lang objc>- (float) sum:(NSMutableArray *)array { int i, sum, value; sum = 0; value = 0;

for (i = 0; i < [array count]; i++) { value = [[array objectAtIndex: i] intValue]; sum += value; }

return suml; }</lang> Product: <lang objc>- (float) prod:(NSMutableArray *)array { int i, prod, value; prod = 0; value = 0;

for (i = 0; i < [array count]; i++) { value = [[array objectAtIndex: i] intValue]; prod *= value; }

return suml; }</lang>

OCaml

Arrays

<lang ocaml>(* ints *) let a = [| 1; 2; 3; 4; 5 |];; Array.fold_left (+) 0 a;; Array.fold_left ( * ) 1 a;; (* floats *) let a = [| 1.0; 2.0; 3.0; 4.0; 5.0 |];; Array.fold_left (+.) 0.0 a;; Array.fold_left ( *.) 1.0 a;;</lang>

Lists

<lang ocaml>(* ints *) let x = [1; 2; 3; 4; 5];; List.fold_left (+) 0 x;; List.fold_left ( * ) 1 x;; (* floats *) let x = [1.0; 2.0; 3.0; 4.0; 5.0];; List.fold_left (+.) 0.0 x;; List.fold_left ( *.) 1.0 x;;</lang>

Octave

<lang octave>a = [ 1, 2, 3, 4, 5, 6 ]; b = [ 10, 20, 30, 40, 50, 60 ]; vsum = a + b; vprod = a .* b;</lang>

Oz

Calculations like this are typically done on lists, not on arrays: <lang oz>declare

 Xs = [1 2 3 4 5]
 Sum = {FoldL Xs Number.'+' 0}
 Product = {FoldL Xs Number.'*' 1}

in

 {Show Sum}
 {Show Product}</lang>

If you are actually working with arrays, a more imperative approach seems natural: <lang oz>declare

 Arr = {Array.new 1 3 0}
 Sum = {NewCell 0}

in

 Arr.1 := 1
 Arr.2 := 2
 Arr.3 := 3
 for I in {Array.low Arr}..{Array.high Arr} do
    Sum := @Sum + Arr.I
 end
 {Show @Sum}</lang>

PARI/GP

<lang>vecsum(v)={

 sum(i=1,#v,v[i])

}; vecprod(v)={

 prod(i=1,#v,v[i])

};</lang>

Perl

<lang perl>my @list = ( 1, 2, 3 );

my ( $sum, $prod ) = ( 0, 1 ); $sum += $_ foreach @list; $prod *= $_ foreach @list;</lang> Alternate:

<lang perl>use List::Util qw( sum reduce ); 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>

Perl 6

Works with: Rakudo version #21 "Seattle"

<lang perl6>my @ary = 1, 5, 10, 100; say 'Sum: ', [+] @ary; say 'Product: ', [*] @ary;</lang>

PHP

<lang php>$array = array(1,2,3,4,5,6,7,8,9); echo array_sum($array); echo array_product($array);</lang>

PicoLisp

<lang PicoLisp>(let Data (1 2 3 4 5)

  (cons
     (apply + Data)
     (apply * Data) ) )</lang>

Output:

(15 . 120)

PL/I

<lang PL/I> declare A(10) fixed binary static initial

  (1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

put skip list (sum(A)); put skip list (prod(A)); </lang>

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;
   ar(i) * prod -> prod;

endfor;</lang> One can alternatively use second order iterator: <lang pop11>lvars sum = 0, prod = 1, ar = {1 2 3 4 5 6 7 8 9}; appdata(ar, procedure(x); x + sum -> sum; endprocedure); appdata(ar, procedure(x); x * prod -> prod; endprocedure);</lang>

PowerShell

The Measure-Object cmdlet already knows how to compute a sum: <lang powershell>function Get-Sum ($a) {

   return ($a | Measure-Object -Sum).Sum

}</lang> But not how to compute a product: <lang powershell>function Get-Product ($a) {

   if ($a.Length -eq 0) {
       return 0
   } else {
       $p = 1
       foreach ($x in $a) {
           $p *= $x
       }
       return $p
   }

}</lang> One could also let PowerShell do all the work by simply creating an expression to evaluate:

Works with: PowerShell version 2

<lang powershell>function Get-Product ($a) {

   if ($a.Length -eq 0) {
       return 0
   }
   $s = $a -join '*'
   return (Invoke-Expression $s)

}</lang> Even nicer, however, is a function which computes both at once and returns a custom object with appropriate properties: <lang powershell>function Get-SumAndProduct ($a) {

   $sum = 0
   if ($a.Length -eq 0) {
       $prod = 0
   } else {
       $prod = 1
       foreach ($x in $a) {
           $sum += $x
           $prod *= $x
       }
   }
   $ret = New-Object PSObject
   $ret | Add-Member NoteProperty Sum $sum
   $ret | Add-Member NoteProperty Product $prod
   return $ret

}</lang> Output:

PS> Get-SumAndProduct 5,9,7,2,3,8,4

Sum Product
--- -------
 38   60480

Prolog

<lang prolog>sum([],0). sum([H|T],X) :- sum(T,Y), X is H + Y. product([],1). product([H|T],X) :- product(T,Y), X is H * X.</lang>

test

:- sum([1,2,3,4,5,6,7,8,9],X).
X =45;
:- product([1,2,3,4,5],X).
X = 120;


Using fold <lang prolog> add(A,B,R):-

   R is A + B.

mul(A,B,R):-

   R is A * B.

% define fold now. fold([], Act, Init, Init).

fold(Lst, Act, Init, Res):-

   head(Lst,Hd),
   tail(Lst,Tl),
   apply(Act,[Init, Hd, Ra]),
   fold(Tl, Act, Ra, Res).

sumproduct(Lst, Sum, Prod):-

   fold(Lst,mul,1, Prod),
   fold(Lst,add,0, Sum).

?- sumproduct([1,2,3,4],Sum,Prod). Sum = 10, Prod = 24 .

</lang>

PostScript

<lang> /sumandproduct { /x exch def /sum 0 def /prod 0 def /i 0 def x length 0 eq { } { /prod prod 1 add def x length{ /sum sum x i get add def /prod prod x i get mul def /i i 1 add def }repeat }ifelse sum == prod == }def </lang>

Library: initlib

<lang postscript> % sum [1 1 1 1 1] 0 {add} fold % product [1 1 1 1 1] 1 {mul} fold

</lang>

PureBasic

<lang PureBasic>Dim MyArray(9) Define a, sum=0, prod=1

For a = 0 To ArraySize(MyArray())  ; Create a list of some random numbers

 MyArray(a) = 1 + Random(9)          ; Insert a number [1...10] in current element

Next

For a = 0 To ArraySize(MyArray())  ; Calculate Sum and Product of this Array

 sum  + MyArray(a)
 prod * MyArray(a)

Next

Debug "The sum is " + Str(sum)  ; Present the results Debug "Product is " + Str(prod)</lang>

Python

Works with: Python version 2.5

<lang python>numbers = [1, 2, 3] total = sum(numbers)

product = 1 for i in numbers:

   product *= i</lang>

Or functionally (faster but perhaps less clear):

Works with: Python version 2.5

<lang python>from operator import mul, add sum = reduce(add, numbers) # note: this version doesn't work with empty lists sum = reduce(add, numbers, 0) product = reduce(mul, numbers) # note: this version doesn't work with empty lists product = reduce(mul, numbers, 1)</lang>

Library: numpy

<lang python>from numpy import r_ numbers = r_[1:4] total = numbers.sum() product = numbers.prod()</lang>

If you are summing floats in Python 2.6+, you should use math.fsum() to avoid loss of precision:

Works with: Python version 2.6, 3.x

<lang python>import math total = math.fsum(floats)</lang>

R

<lang r>total <- sum(1:5) product <- prod(1:5)</lang>

Raven

<lang raven>0 [ 1 2 3 ] each + 1 [ 1 2 3 ] each *</lang>

REBOL

<lang REBOL>REBOL [

   Title: "Sum and Product"
   Date: 2010-01-04
   Author: oofoe
   URL: http://rosettacode.org/wiki/Sum_and_product_of_array

]

Simple

sum: func [a [block!] /local x] [x: 0 forall a [x: x + a/1] x]

product: func [a [block!] /local x] [x: 1 forall a [x: x * a/1] x]

Way too fancy

redux: func [ "Applies an operation across an array to produce a reduced value." a [block!] "Array to operate on." op [word!] "Operation to perform." /init x "Initial value (default 0)." ][if not init [x: 0] forall a [x: do compose [x (op) (a/1)]] x]

rsum: func [a [block!]][redux a '+]

rproduct: func [a [block!]][redux/init a '* 1]

Tests

assert: func [code][print [either do code [" ok"]["FAIL"] mold code]]

print "Simple dedicated functions:" assert [55 = sum [1 2 3 4 5 6 7 8 9 10]] assert [3628800 = product [1 2 3 4 5 6 7 8 9 10]]

print [crlf "Fancy reducing function:"] assert [55 = rsum [1 2 3 4 5 6 7 8 9 10]] assert [3628800 = rproduct [1 2 3 4 5 6 7 8 9 10]]</lang>

Output:

Simple dedicated functions:
  ok [55 = sum [1 2 3 4 5 6 7 8 9 10]]
  ok [3628800 = product [1 2 3 4 5 6 7 8 9 10]]

Fancy reducing function:
  ok [55 = rsum [1 2 3 4 5 6 7 8 9 10]]
  ok [3628800 = rproduct [1 2 3 4 5 6 7 8 9 10]]

REXX

<lang rexx> /*REXX program to add and seperately multiply elements of an array. */

numeric digits 30 /*allow 30-digit numbers (default is 9)*/

y.0=20 /*one method of indicating array size. */

 do j=1 for y.0             /*build an array of twenty elements.   */
 y.j=j                      /*set 1st to 1, 3rd to 3, 9th to 9 ... */
 end



sum=0 /*initialize SUM to zero. */ prod=1 /*initialize PROD to unity. */

 do k=1 for y.0
 sum =sum +y.k              /*add the element to the running total.*/
 prod=prod*y.k              /*multiple the element to running prod.*/
 end

say ' sum of' y.0 "elements for the Y array is:" sum say 'product of' y.0 "elements for the Y array is:" prod </lang> Output:

    sum of 20 elements for the Y array is: 210
product of 20 elements for the Y array is: 2432902008176640000

Ruby

<lang ruby>arr = [1,2,3,4,5] # or ary = *1..5, or ary = (1..5).to_a sum = arr.inject(0) { |sum, item| sum + item }

  1. => 15

product = arr.inject(1) { |prod, element| prod * element }

  1. => 120</lang>
Works with: Ruby version 1.9

<lang ruby>arr = [1,2,3,4,5] sum = arr.inject(0, :+)

  1. => 15

product = arr.inject(1, :*)

  1. => 120</lang>

Sather

<lang sather>class MAIN is

 main is
   a :ARRAY{INT} := |10, 5, 5, 20, 60, 100|;
   sum, prod :INT;
   loop sum := sum + a.elt!; end;
   prod := 1;
   loop prod := prod * a.elt!; end;
   #OUT + sum + " " + prod + "\n";
 end;

end;</lang>

Scala

Functional style <lang scala>val array = Array(1,2,3,4,5) val sum = array.reduceLeft(_+_) val product = array.reduceLeft(_*_) // (_+_) is a shortcut for {(x,y) => x + y}</lang> Imperative style <lang scala>val array = Array(1,2,3,4,5) var sum = 0; var product = 1 for (val x <- array) sum += x for (val x <- array) product *= x</lang>

Scheme

<lang scheme>(apply + '(1 2 3 4 5)) (apply * '(1 2 3 4 5))</lang> 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. <lang scheme>(define (reduce f i l)

 (if (null? l)
   i
   (reduce f (f i (car l)) (cdr l))))

(reduce + 0 '(1 2 3 4 5)) ;; 0 is unit for + (reduce * 1 '(1 2 3 4 5)) ;; 1 is unit for *</lang>

Seed7

<lang seed7>const func integer: sumArray (in array integer: valueArray) is func

 result
   var integer: sum is 0;
 local
   var integer: value is 0;
 begin
   for value range valueArray do
     sum +:= value;
   end for;
 end func;

const func integer: prodArray (in array integer: valueArray) is func

 result
   var integer: prod is 1;
 local
   var integer: value is 0;
 begin
   for value range valueArray do
     prod *:= value;
   end for;
 end func;</lang>

Call these functions with:

writeln(sumArray([](1, 2, 3, 4, 5)));
writeln(prodArray([](1, 2, 3, 4, 5)));

SETL

<lang SETL>numbers := [1 2 3 4 5 6 7 8 9]; print(+/ numbers, */ numbers);</lang>

=> 45 362880

Slate

<lang slate>#(1 2 3 4 5) reduce: [:sum :number | sum + number]

  1. (1 2 3 4 5) reduce: [:product :number | product * number]</lang>

Shorthand for the above with a macro: <lang slate>#(1 2 3 4 5) reduce: #+ `er

  1. (1 2 3 4 5) reduce: #* `er</lang>

Smalltalk

<lang smalltalk>#(1 2 3 4 5) inject: 0 into: [:sum :number | sum + number]

  1. (1 2 3 4 5) inject: 1 into: [:product :number | product * number]</lang>

Some implementation also provide a fold: message: <lang smalltalk>#(1 2 3 4 5) fold: [:sum :number | sum + number]

  1. (1 2 3 4 5) fold: [:product :number | product * number]</lang>

SNOBOL4

<lang snobol> t = table()

  • read the integer from the std. input

init_tab t<x = x + 1> = trim(input) :s(init_tab)

         product = 1
         sum = 0
  • counting backwards to 1

loop i = t< x = ?gt(x,1) x - 1> :f(out)

         sum = sum + i
         product = product * i         :(loop)

out output = "Sum: " sum

         output = "Prod: " product

end</lang>

Input

1
2
3
4
5

Output

Sum:  15
Prod: 120

Standard ML

Arrays

<lang sml>(* ints *) val a = Array.fromList [1, 2, 3, 4, 5]; Array.foldl op+ 0 a; Array.foldl op* 1 a; (* reals *) val a = Array.fromList [1.0, 2.0, 3.0, 4.0, 5.0]; Array.foldl op+ 0.0 a; Array.foldl op* 1.0 a;</lang>

Lists

<lang sml>(* ints *) val x = [1, 2, 3, 4, 5]; foldl op+ 0 x; foldl op* 1 x; (* reals *) val x = [1.0, 2.0, 3.0, 4.0, 5.0]; foldl op+ 0.0 x; foldl op* 1.0 x;</lang>

Tcl

<lang tcl>set arr [list 3 6 8] set sum [expr [join $arr +]] set prod [expr [join $arr *]]</lang>

Works with: Tcl version 8.5

<lang tcl>set arr [list 3 6 8] set sum [tcl::mathop::+ {*}$arr] set prod [tcl::mathop::* {*}$arr]</lang>

TI-83 BASIC

Use the built-in functions

sum()

and

prod()

.

Toka

<lang toka>4 cells is-array foo

212 1 foo array.put 51 2 foo array.put 12 3 foo array.put 91 4 foo array.put

[ ( array size -- sum )

 >r 0 r> 0 [ over i swap array.get + ] countedLoop nip ] is sum-array
( product )

reset 1 4 0 [ i foo array.get * ] countedLoop .</lang>

Trith

<lang trith>[1 2 3 4 5] 0 [+] foldl</lang> <lang trith>[1 2 3 4 5] 1 [*] foldl</lang>

UNIX Shell

Works with: NetBSD version 3.0

From an internal variable, $IFS delimited:

<lang bash>sum=0 prod=1 list="1 2 3" for n in $list do sum="$(($sum + $n))"; prod="$(($prod * $n))" done echo $sum $prod</lang>

From the argument list (ARGV):

<lang bash>sum=0 prod=1 for n do sum="$(($sum + $n))"; prod="$(($prod * $n))" done echo $sum $prod</lang>

From STDIN, one integer per line:

<lang bash>sum=0 prod=1 while read n do sum="$(($sum + $n))"; prod="$(($prod * $n))" done echo $sum $prod</lang>

Works with: GNU bash version 3.2.0(1)-release (i386-unknown-freebsd6.1)

From variable:

<lang bash>LIST='20 20 2'; SUM=0; PROD=1; for i in $LIST; do

 SUM=$[$SUM + $i]; PROD=$[$PROD * $i];

done; echo $SUM $PROD</lang>

UnixPipes

<lang bash>prod() {

  (read B; res=$1; test -n "$B" && expr $res \* $B || echo $res)

}

sum() {

  (read B; res=$1; test -n "$B" && expr $res + $B || echo $res)

}

fold() {

  (func=$1; while read a ; do ; fold $func | $func $a done)

}


(echo 3; echo 1; echo 4;echo 1;echo 5;echo 9) | tee >(fold sum) >(fold prod) > /dev/null</lang>

Ursala

The reduction operator, :-, takes an associative binary function and a constant for the empty case. Natural numbers are unsigned and of unlimited size. <lang Ursala>#import nat

  1. cast %nW

sp = ^(sum:-0,product:-1) <62,43,46,40,29,55,51,82,59,92,48,73,93,35,42,25></lang> output:

(875,2126997171723931187788800000)

V

<lang v>[sp dup 0 [+] fold 'product=' put puts 1 [*] fold 'sum=' put puts].</lang> Using it <lang v>[1 2 3 4 5] sp = product=15 sum=120</lang>

XSLT

XSLT (or XPath rather) has a few built-in functions for reducing from a collection, but product is not among them. Because of referential transparency, one must resort to recursive solutions for general iterative operations upon collections. The following code represents the array by numeric values in <price> elements in the source document.

<lang xml><xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

 <xsl:output method="text" />
 
 <xsl:template name="sum-prod">
   <xsl:param name="values" />
   <xsl:param name="sum"  select="0" />
   <xsl:param name="prod" select="1" />
   <xsl:choose>
     <xsl:when test="not($values)">
       <xsl:text>

Sum: </xsl:text>

       <xsl:value-of select="$sum" />
       <xsl:text>

Product: </xsl:text>

       <xsl:value-of select="$prod" />
     </xsl:when>
     <xsl:otherwise>
       <xsl:call-template name="sum-prod">
         <xsl:with-param name="values" select="$values[position() > 1]" />
         <xsl:with-param name="sum"  select="$sum  + $values[1]" />
         <xsl:with-param name="prod" select="$prod * $values[1]" />
       </xsl:call-template>
     </xsl:otherwise>
   </xsl:choose>
 </xsl:template>
 
 <xsl:template match="/">
    <xsl:text>

Sum (built-in): </xsl:text>

   <xsl:value-of select="sum(//price)" />
   
   <xsl:call-template name="sum-prod">
     <xsl:with-param name="values" select="//price" />
   </xsl:call-template>
 </xsl:template>

</xsl:stylesheet></lang>