See ArraySum for problem description and context. (List now alphabeticized for your convenience) ---- AplLanguage: X <- +/A ---- AwkLanguage: function array_sum(a, i,s) { for (i in a) s+=a[i] return s } ---- CeePlusPlus: template typename Container::value_type containerSum(const Container& container) { return std::accumulate( container.begin(), container.end(), Container::value_type(0)); } or template vector::value_type ArraySum(vector &array) { T retVal; int cntr; for(cntr = 0 ; cntr < array.size() ; cntr++) { cntr==0?retVal =array[0]:retVal += array[cntr]; } return retVal; } Will work if T has an '=' and a '+' operator. see GrokBranching (before modifying above algorithm) or you could use a higher level library such as Blitz++, BlitzPlusPlus sum( A ); Two more modern C++11 versions: template auto Sum(T input) -> typename T::value_type { typename T::value_type result{}; for(auto x : input) result += x; return result; } template auto Sum(std::initializer_list input) -> T { auto j = begin(input); auto result = *j++; for(; j != end(input); ++j) result += *j; return result; } The former works with any container that supports begin() and end(), the latter works with bare initializer lists and uses a slightly more "correct" loop: auto data = std::vector{1, 2, 3, 4, 5}; auto data = std::list{1, 2, 3, 4, 5}; auto data = std::array{{1, 2, 3, 4, 5}}; cout << Sum(data) << endl; cout << Sum({1, 2, 3, 4, 5}) << endl; The following will work (C++11) for arrays, initializer_lists, valarrays, and any container that exposes appropriate begin() and end() methods. It may be made to work for other types by specializing std::begin and std::end for those types. std::vector data{1, 2, 3, 4, 5}; int sum = 0; std::for_each(std::begin(data), std::end(data), [&](int item){ sum += item; }); ---- CsharpLanguage: The most direct and efficient way to go is this: int[] numbers = { 1, 2, 3, 4, 5 }; int sum = 0; foreach (int n in numbers) sum += n; This can also be written using the generic Aggregate operator defined by LINQ over any sequence of values. int[] numbers = { 1, 2, 3, 4, 5 }; int sum = numbers.Aggregate((a, b) => a + b); LINQ also predefines the Min, Max, Average, and Sum aggregates, which means you can just write it like this: int[] numbers = { 1, 2, 3, 4, 5 }; int sum = numbers.Sum(); -- DonBox ---- CommonLisp: (defun sum-sequence (s) (reduce #'+ s)) (sum-sequence '(1 2 3)) -> 6 ''This won't work with CL arrays of rank > 1, which seems to be the point of this page'' ''''I'm not sure where the requirement can be read that it has to work on arrays of rank > 1. Are the other examples for other languages with multi-dimensional arrays taking care of it? What do you think? (The CL example that is given later on this page for example might give errors if the array has a fill-pointer.)'''' For those who prefer something a bit more amusing: (defun sum-sequence (seq) (loop for x across seq summing x)) Loop is just amusing. ---- CoqAssistant: Require Import List. Require Import Arith. Definition arraysum a := fold_left plus a O. Fixpoint running_sum a l {struct l} := %l decreases with every recursive call a :: match l with | nil => nil | cons b l' => running_sum (plus a b) l' end. Check sum. sum : list nat -> nat Eval compute in sum (1::2::3::nil). = 6 : nat Check running_sum. running_sum : nat -> list nat -> list nat Eval compute in running_sum 0 (1::2::3::nil). = 0::1::3::6::nil : list nat ---- DeeCee To consume the whole main stack, here is a macro "S": [+z1 cell+ ; : tableSize cell- @ ; : tableSum 0 over dup tableSize cells + rot ( sum extent table ) ?do I @ + cell +loop ; 4 table aTable 1 , 2 , 3 , 4 , aTable tableSum . \ 10 ---- HaskellLanguage: The HaskellLanguage equivalent of reduce are the foldl and foldr higher order functions. They both have the same behaviour when used with the + operator (note that parenthesising an operator turns it into a function): arraysum = foldl (+) 0 This idiomatic use of currying is equivalent to: arraysum a = foldl (+) 0 a And it's good practice to explicitly declare the function type, although the compiler can infer the type from it's use: arraysum :: Num a => [a] -> a To produce the running sum, we use a counterpart to foldl: scanl, which produces each step of "folding" the operator in. runningsum ns = tail $ scanl (+) 0 ns Giving a type of: runningsum :: (Num a) => [a] -> [a] Even simpler: arraysum = sum ---- IokeLanguage: a inject(+) Or, equivalently: a fold(+) or: a reduce(+) These three are actually identical (they're names for identical macros). They work on any type which understands "+", including strings. ---- J (JayLanguage): +/A Note that this works on arrays of any rank, producing an array of one less than that rank. Thus, the sum reduces the array by the last axis. This behavior is more formal in J (JayLanguage) than in AplLanguage (see below). By the way, the reducing operation doesn't have to be plus - it can be any "binary" (we call them dyadic) function - such as multiply. Just replace the "+" with the appropriate primitive. For even more fun, +/\A Produces the RUNNING sums. ---- JavaLanguage: Proper software engineers should not use one-liners. So, here is a Java version: public interface Operator { public Object apply( Object lhs, Object rhs ) ; } public class Collect''''''Operator implements Operator { private Operator op; public Collect''''''Operation( Operator op ) { this.op = op ; } public Object apply( Collection coll, Object start ) { Object accumulator = start ; Iterator it = coll.iterator() ; while (it.hasNext()) { Object obj = it.next() ; accumulator = op.apply( accumulator, obj ) ; } return accumulator ; } } public class Int''''''Array''''''List extends Abstract''''''List { private int[] arr ; public Int''''''Array''''''List( int[] arr ) { this.arr = arr ; } public int size() { return arr.length ; } public Object get( int index ) { int i = arr[index] ; return new Integer( i ) ; } } public class Add''''''Operator implements Operator { public Object apply( Object lhs, Object rhs ) { int l = ((Integer)lhs).intValue() ; int r = ((Integer)rhs).intValue() ; int sum = l + r ; return new Integer( sum ) ; } } public int arraySum ( int[] arr ) { List l = new Int''''''Array''''''List( arr ) ; Operator add = new Add''''''Operator() ; Operator collectAdd = new Collect''''''Operator( add ) ; Object sum = collectAdd.apply( l ) ; return ((Integer)sum).intValue() ; } As you can see, Java is a far superior language to all others! -- TomAnderson Hehehe... a serious case of YouArentGonnaNeedIt-itis with BigDesignUpFront complications. Here's a simple version: public static int sum( int[] a ) { int sum = 0; for( int i = 0; i < a.length; i++ ) sum += a[i]; return sum; } /** * Java 5.0. */ // Returns the sum of the elements of array a // (blatantly plagarized from http://java.sun.com/j2se/1.5.0/docs/guide/language/foreach.html ) public static int sum(int[] a) { int result = 0; for (int n : a) result += n; return result; } ---- JavaScript: As a PrototypeBasedLanguage, it is most convenient to add this method to the base Array object via its prototype: Array.prototype.sum = function() { var n = 0; for (var i=0; i 10 ''And, as always, there's a better way to do it'' def sumArray(a) a.inject(0) { |sum, value| sum + value } end ''And then there's the slightly more general expression, which returns nil as its "0", but works for all types of lists'' def sum a a.inject { |sum, i| sum + i } end ----- '''ScalaLanguage''' def sum(a: Int*) = (0 /: a) (_ + _) Lest you conclude that ScalaLanguage is an incomprehensible language, let me point out that "/:" is right-associative synonym for "foldLeft" and "(_ + _)" is shorthand for ((i, j) => i + j) so the above could be equivalently written: def sum(a: Int*) = (a foldLeft 0) ((i, j) => i + j) Or with more Java-like syntax: def sum(a: Int*) = a.foldLeft(0) {(i, j) => i + j } Scala 2.8 now has it built in to all collections so the above function is simply: def sum(a: Int*) = a sum ---- SchemeLanguage: At last, a chance to show off the '''do''' construct of the SchemeLanguage: (define (vector-sum vec) (do ((i 0 (+ i 1)) (sum 0 (+ sum (vector-ref vec i)))) ((= i (vector-length vec)) sum))) (vector-sum '#(1 2 3)) ''Doesn't Scheme have a fold/reduce/collect/whatever function?'' [He's kidding. I hope. Presumably springboarding off the above Java joke. ] ''Actually, while R5RS does not define any of them, one of the SchemeRequestsForImplementation (SRFI-1, List Library) has a full complement of fold and reduce functions. Thus, in an implementation that supports SRFI-7 and SRFI-1, one could write,'' (program (requires srfi-1)) (fold + 0 '(1 2 3 4 5)) ''Mind you, these are ''list'' reduction functions, and so technically do not fit the problem description. That's OK, though, since writing a fold-vector function would be fairly easy:'' (define (fold-right-vector op initial vec) (let ((endpoint (- (vector-length vec) 1))) (if (> 0 endpoint) initial (begin (op initial (let accumulate ((count 0)) (if (>= count endpoint) (vector-ref vec count) (op (vector-ref vec count) (accumulate (add1 count)))))))))) (define (vector-sum vec) (fold-right-vector + 0 vec)) (vector-sum #(1 2 3 4 5)) ''(note that this code has only been cursorily tested and may have bugs). Of course, one could use ''(vector->list)'' and then apply the list ''(fold)'', but that doesn't exactly match the problem. Adapting this to work with homogeneous-numeric vectors (SRFI 4) or multidimensional arrays (SRFI 25) is left as an exercise. - JayOsako'' You can sum lists in Scheme by (define (list-sum lst) (apply + lst)) Aren't Scheme implementations allowed to have a smallish upper limit on how many arguments you can pass to a procedure? If so, that solution might not work for long lists. ''I see '''one''' argument there.'' Then look again. The elements of ''lst'' are being turned into arguments to ''+''. If there are more elements in the list than your implementation's limit on args passed to a procedure, then you lose. ''It is exactly '''one''' argument. The list is not expanded into its elements. However, the task was to give a sum function for '''arrays'''. Since there are no native arrays in Scheme (just like C), the function does not deal with arrays. As for vectors, you either have to resort to the function given above or use (vector->list array) in the second version with some overhead.'' That's certainly how it is in CommonLisp. In CommonLisp you'd use REDUCE: (defun sum-sequence (s) (reduce #'+ s :initial-value 0)), which works for both lists and vectors. Common lisp actually has a (multivariate) array type, so in that case you could do something like (defun sum-array (a) (loop for n below (array-total-size a) summing (row-major-aref a n))) ----- SmalltalkLanguage: myArray := #(1 2 3 4 5). sum := myArray detectSum: [ :n | n + 0 ]. ''Except that #detectSum: isn't part of redbook Smalltalk. Try this instead:'' '''Array>>sum''' ^self inject: 0 into: [:each :sum | each + sum] ------ '''SmlLanguage''' Lines starting with a dash contain the code. Other lines have been printed by the compiler. Standard ML of New Jersey v110.57 [built: Fri Feb 10 21:37:49 2006] - val intArraySum = Array.foldl op+ 0 ; [autoloading] [library $SMLNJ-BASIS/basis.cm is stable] [autoloading done] val intArraySum = fn : int array -> int - val realArraySum = Array.foldl op+ 0.0 ; val realArraySum = fn : real array -> real - intArraySum (Array.tabulate (10, fn i => i)) ; val it = 45 : int - realArraySum (Array.tabulate (10, real)) ; val it = 45.0 : real ------ SqlLanguage (assuming your "array" is a column of a table): select sum(x) from a ------ SwiftLanguage: a.reduce(0) { $0 + $1 } ------ TclLanguage: (In tcl a 'list' is the equivalent of a numerically indexed array) if {[llength $arr]} {expr [join $arr +]} {expr 0} ''or - if using Tcl's associative 'arrays' '' set sum 0 foreach {nm val} [array get arrName] { incr sum $val } ---- VisualBasicNine: The most direct and efficient way to go is this: Dim numbers%() = { 1, 2, 3, 4, 5 } Dim sum = 0 For Each n In numbers sum = sum + n Next This can also be written using the generic Aggregate operator defined by LINQ over any sequence of values. Dim numbers%() = { 1, 2, 3, 4, 5 } Dim sum = numbers.Aggregate(Function(a, b) a + b) LINQ also predefines the Min, Max, Average, and Sum aggregates, which means you can just write it like this: Dim numbers%() = { 1, 2, 3, 4, 5 } Dim sum = numbers.Sum() -- DonBox ---- VisualBasicForApplications: W''''''orksheetFunction.sum(anArray) ---- ExBase * Populate an array. DIMENSION aSumArray[10] FOR x = 1 TO 10 aSumArray(x) = x ENDFOR * Sum its contents. LOCAL oursum oursum = 0 FOR x = 1 TO ALEN(aSumArray) oursum = oursum + aSumArray(x) ENDFOR -- KenDibble ---- Contributors: Various AnonymousDonor''''''s, TomAnderson, EarleMartin ---- This is the type of problem in which CollectionOrientedProgramming languages are clearly better geared for. ---- Also see CounterInManyProgrammingLanguages, DotProductInManyProgrammingLanguages, HelloWorldInManyProgrammingLanguages, WardNumberInManyProgrammingLanguages, BetterForLoopConstruct ---- CategoryInManyProgrammingLanguages