Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enhanced For Loop not adding up elements in array

Tags:

java

java-8

I'm trying to add up the elements in the array with an enhanced for loop. If I do it with a normal for loop, it works. But when I'm using an enhanced for loop it throws an IndexOutOfBounds exception and I'm not sure why that's happening?

int[ ] array = {1,2,3};
int total = 0; 
for(int counter : array) {
    total = total + array[counter];
}
System.out.println(total);
like image 203
Neo Avatar asked Feb 13 '26 18:02

Neo


2 Answers

counter is not index, its the element. You need to add the counter to total.

If you are using Java 8 then you can simplify it to:

int[ ] array = {1,2,3};
System.out.println(Arrays.stream(array).sum());

If you would still like to do it without streams:

int[ ] array = {1,2,3};
int total = 0; 
for(int counter : array) {
    total = total + counter;
}
System.out.println(total);
like image 66
Aniket Sahrawat Avatar answered Feb 15 '26 08:02

Aniket Sahrawat


As Aniket previoysly said, counter is not an index.

Your code is a shorter version of this code:

 for (int i = 0; i<array.size; i++){
     counter = array[i];
     total = total + counter;
 }

As you can see, counter becomes the element of array[i] and i is the index of the array.

If you wanted to keep track of the index using your version of the code, you would have to create an outside variable called i = 0 and increment it by one each repetition.

 int i = 0
 for (counter : array){
     i++;
     counter = array[i];
     total = total + counter;
 }
like image 37
Eduardo Morales Avatar answered Feb 15 '26 07:02

Eduardo Morales