'Dead code in eclipse when trying to find the sum of an array
I tried to find the sum of any array by using the for loop but the i++ part ended up being the deadcode unreachable. I don't understand why?
public static int sum(int[] data) {
int sum = 0;
int i;
for (i = 0; i < data.length; i++) { //the i ++ is the deadcode
sum += data [i];
return sum;
}
return 0;
}
Solution 1:[1]
The i++
is dead code because it can never be reached. It can never be reached because you have a return statement within the loop. Therefore, it will never execute the increment portion of the for-loop. Move the return sum;
outside the loop (replacing the return 0;
).
public static int sum(int[] data) {
int sum = 0;
for (int i = 0; i < data.length; i++) {
sum += data [i];
}
return sum;
}
Solution 2:[2]
Don't return something inside for loop, because return ends the cycle of whole function.
Instead, do something like this:
public static int sum(int[] data) {
int sum = 0;
for (int i = 0; i < data.length; i++) {
sum += data[i];
}
return sum;
}
Solution 3:[3]
You are always returning after the first iteration so you do not sum anything besides the first element. You should do it like this :
public static int sum(int[] data) {
int sum = 0;
for (int i = 0; i < data.length; i++)
{
sum += data [i];
}
return sum;
}
public static void main(String[] args)
{
int data[] = {1,2,3,4,5};
int sum = sum(data);
System.out.println(sum);
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | vsfDawg |
Solution 2 | xEdziu |
Solution 3 |