Internet Posted April 25, 2008 Share Posted April 25, 2008 Is there a java function that sums up all of the elements of an array? because i don't want to have to write out a loop to count it or do array[1] + array[2] etc...... Link to comment Share on other sites More sharing options...
0 Laurë Veteran Posted April 25, 2008 Veteran Share Posted April 25, 2008 No idea, check the API http://java.sun.com/j2se/1.5.0/docs/api/ A loop would take two minutes to write though.. Link to comment Share on other sites More sharing options...
0 The2 Posted April 25, 2008 Share Posted April 25, 2008 Yes. It's called for (int i=0; i < arr.length; i++) sum+=arr; Link to comment Share on other sites More sharing options...
0 abshack Posted April 25, 2008 Share Posted April 25, 2008 Yes. It's calledfor (int i=0; i < arr.length; i++) sum+=arr; +1. Link to comment Share on other sites More sharing options...
0 tiagosilva29 Posted April 25, 2008 Share Posted April 25, 2008 int sum = 0; for (int i : array) { sum += i; } Link to comment Share on other sites More sharing options...
0 Andre S. Veteran Posted April 26, 2008 Veteran Share Posted April 26, 2008 AFAIK there is none, and it would be normal because the java array is designed to hold any kind of object, not just integers or types that can be summed together. If you really need a sum() method for your arrays, just create your own Array class by extending the Java Array class. Link to comment Share on other sites More sharing options...
0 loople Posted April 26, 2008 Share Posted April 26, 2008 Or use C# Framework 3.5 and just use partial methods to extend the actual arraylist class! (This saves you referencing a user defined class everywhere) C# FTW! ;) Link to comment Share on other sites More sharing options...
Question
Internet
Is there a java function that sums up all of the elements of an array? because i don't want to have to write out a loop to count it or do array[1] + array[2] etc......
Link to comment
Share on other sites
6 answers to this question
Recommended Posts