javaloopsdead-code

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

  • 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;
    }