Reputation: 35
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;
}
Upvotes: 1
Views: 71
Reputation:
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);
}
}
Upvotes: 1
Reputation: 1527
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;
}
Upvotes: 1
Reputation: 125
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;
}
Upvotes: 1