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; //to be completed
}
CodePudding user response:
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;
}
CodePudding user response:
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;
}
CodePudding user response:
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);
}
}