Home > Mobile >  Why do I need to write duplicate condition in this while loop?
Why do I need to write duplicate condition in this while loop?

Time:06-29

I'm working on the code returns the maximum number of consecutive 1's in the array. I used two while loops for this code.

public int findMaxConsecutiveOnes(int[] nums) {
    int maximum = 0;
    int i = 0;
    while (i < nums.length) {
        int conOnes = 0;
        while (i < nums.length && nums[i] == 1) {
            conOnes  ;
            i  ;
        }
        maximum = Math.max(maximum, conOnes);
        i  ;
    }
    return maximum;
}

I already wrote i < nums.length in the first while loop condition, so I thought I don't need to write i < nums.length in the second while loop condition again. But when I omit i < nums.length && from the second one, it causes java.lang.ArrayIndexOutOfBoundsException: Index 6 out of bounds for length 6. As the second while loop never be executed when i > nums.length,I don't get why I got this IOB exception.

CodePudding user response:

You might not need inner loop:

  public int findMaxConsecutiveOnes(int[] nums) {
    int maximum = 0;
    int i = 0;
    int conOnes = 0;
    while (i < nums.length) {

      if (nums[i] == 1) {
        conOnes  ;
      } else {
        conOnes = 0;
      }
      maximum = Math.max(maximum, conOnes);
      i  ;
    }
    return maximum;
  }

CodePudding user response:

What you maybe not realize is that the condition for a loop is only checked after completing a full iteration. It doesn't automatically jump out of the loop once the condition is met. So to demonstrate, consider this code:

int i = 0;
while (i < 5) {
    while (i < 10) {
        i  ;
    }
}
System.out.println(i); //this will print 10

So it doesn't matter that the condition of the outer loop was met after an interation of the inner loop

  • Related