Product of Array: Difference between revisions
Content deleted Content added
m fixed redirect since multiple redirects aren't followed |
|||
(60 intermediate revisions by 38 users not shown) | |||
Line 1: | Line 1: | ||
#REDIRECT [[Sum and product of an array]] |
|||
{{task}} |
|||
Compute the product of the elements of an Array |
|||
==[[C sharp|C#]]== |
|||
[[Category:C sharp|C#]] |
|||
int value = 1; |
|||
int[] arg = { 1,2,3,4,5 }; |
|||
int arg_length = arg.Length; |
|||
for( int i = 0; i < arg_length; i++ ) |
|||
value *= arg[i]; |
|||
Alternate |
|||
int prod = 1; |
|||
int[] arg = { 1, 2, 3, 4, 5 }; |
|||
foreach (int value in arg) prod *= value; |
|||
==[[C plus plus|C++]]== |
|||
[[Category:C plus plus|C++]] |
|||
int value = 1; |
|||
int arg[] = { 1,2,3,4,5 }; |
|||
int arg_length = sizeof(arg)/sizeof(arg[0]); |
|||
int *end = arg+arg_length; |
|||
for( int *p = arg; p!=end; ++p ) |
|||
value *= *p; |
|||
==[[FreeBASIC]]== |
|||
[[Category:FreeBASIC]] |
|||
dim array(4) as integer = { 1, 2, 3, 4, 5 } |
|||
dim product as integer = 1 |
|||
for index as integer = lbound(array) to ubound(array) |
|||
product *= array(index) |
|||
next |
|||
==[[Haskell]]== |
|||
[[Category:Haskell]] |
|||
let x = [1..10] |
|||
product x -- the easy way |
|||
foldl (*) 1 x -- the hard way |
|||
==[[Java]]== |
|||
[[Category:Java]] |
|||
int[] arg = { 1,2,3,4,5 }; |
|||
int value = 1; |
|||
for (int i: arg) |
|||
value *= arg; |
|||
==[[OCaml]]== |
|||
[[Category:OCaml]] |
|||
let x = [|1; 2; 3; 4; 5; 6; 7; 8; 9; 10|];; |
|||
Array.fold_left ( * ) 1 x |
|||
Variant, using a liked list rather than an array: |
|||
let x = [1; 2; 3; 4; 5; 6; 7; 8; 9; 10];; |
|||
List.fold_left ( * ) 1 x |
|||
==[[PHP]]== |
|||
[[Category:PHP]] |
|||
$array = array(1, 2, 3); |
|||
$sum = array_sum($array); |
|||
echo($sum); |
|||
Alternate |
|||
$array = array(1, 2, 3); |
|||
$sum = 0; |
|||
foreach($array as $key) |
|||
{ |
|||
$sum += $key; |
|||
} |
|||
echo($sum); |
|||
==[[Perl]]== |
|||
[[Category:Perl]] |
|||
'''Interpeter:''' [[Perl]] |
|||
my $var; |
|||
my @list = (1, 2, 3); |
|||
map($var *= $_, @list); |
|||
Alternate |
|||
my $var; |
|||
my @list = (1, 2, 3); |
|||
$var *= $_ for (@list); |
|||
==[[Python]]== |
|||
[[Category:Python]] |
|||
'''Interpreter:''' [[Python]] 2.5 |
|||
x = [1, 2, 3, 4, 5, 6, 7, 8, 9] |
|||
product = 1 |
|||
for i in x: |
|||
product *= i |
|||
or |
|||
reduce(lambda z, y: z * y, x) |
|||
'''Note:''' It is encouraged not to use this as reduce may go away in the future. |
|||
==[[Ruby]]== |
|||
[[Category:Ruby]] |
|||
ary = [1,2,3,4,5] |
|||
product = ary.inject{|currentProduct,element|currentProduct*element} |
|||
# => 120 |
|||
==[[Scheme]]== |
|||
[[Category:Scheme]] |
|||
(define x '(1 2 3 4 5)) |
|||
(apply * x) |
|||
==[[Standard ML]]== |
|||
[[Category:Standard ML]] |
|||
val x = [1,2,3,4,5] |
|||
foldl (op*) 1 x |
Latest revision as of 08:39, 2 July 2010
Redirect to: