Total values in an Array - Java

Tarrant64

Diamond Member
Sep 20, 2004
3,203
0
76
Right now since there was only a few values I had to total in an array I just did it the long way:

ex: sum of all hours worked in a work week stored in an array( of 5)

totalHours = hours[0] + hours[1] + hours[2] + hours[3] + hours[4]

Any shorter way to do this? I was fortunate enough to only have an array of 5 elements, however I know I should plan for cases of any variable length.
 

ahurtt

Diamond Member
Feb 1, 2001
4,283
0
0
for loop.

Lets say you have an array of int named "intArray" that has length of 5.


This will work with an array of any size. You may want to make your "total" variable a long instead of an int if you think there is a chance your total may overflow the maximum value an int can hold. (Following code sample in Java).


GRRRR. . .stupid forum munged up my code formatting :| WHY would you have a programming forum that doesn't preserve formatting of code samples?
 

mundane

Diamond Member
Jun 7, 2002
5,603
8
81
Java 5 has an improved for loop iteration with better syntax:

Edit: I echo your sentiments - at one time, the attach-code worked correctly
 

stevf

Senior member
Jan 26, 2005
290
0
0
this is a good case for the improved for loop - also called for each loop - this came in in java 5 i believe and works with arrays & collections - here is Java's tutorial on it:

http://java.sun.com/docs/books.../nutsandbolts/for.html


but you want:

//assuming you have an int array - change the type to match the array and the counter variable
int totalHours = 0;
for (int total: hours) {
totalHours += hours;
}

this will step completely through the array without having to worry about out of bounds errors, etc


edit - at work so i may have that syntax off a bit but the link is for Sun's Tutorial and they have lots of good stuff there

more edit - ok it is clear to me now - this is how that should look
int totalHours = 0;
for (int dailyHours : hours) {
totalHours += dailyHours;
}