Home > Software engineering >  Is it possible to for loop last index to first index in enhanced loop?
Is it possible to for loop last index to first index in enhanced loop?

Time:05-24

I was wondering about this, We can use enhanced for instead of regular for loop in this case

for (int i = 0; i < arr.length; i  ) {

        System.out.println(arr[i]);

    }


    for (int temp : arr) {

        System.out.println(temp);

    }

Can I use enhanced for in this case?

    for (int i = arr.length; i <= 0; i--) {

        System.out.println(arr[i]);
    }

CodePudding user response:

None of the suggested duplicates actually seem to give the solution for an array rather than a list.

Unfortunately, there's no way to do it without boxing and unboxing.

Iterable<Integer> reverse(final int[] arr) {
    return () -> new Iterator<Integer>() {
        private int curr = arr.length - 1;
        
        @Override
        public boolean hasNext() {
            return curr >= 0;
        }
        
        @Override
        public Integer next() {
            if (curr < 0) {
                throw new NoSuchElementException("exhausted");
            }
            return arr[curr--];
        }
    };
}

(Maybe in Valhalla boxing and unboxing won't be necessary.)

Usage:

for (int x : new int[] {1, 2, 3}) System.out.println(x);
1
2
3
for (int x : reverse(new int[] {1, 2, 3})) System.out.println(x);
3
2
1

CodePudding user response:

As per language specification ,

for (initialization; termination;
     increment) {
    statement(s)
}

so, in your enhanced case, you are incrementing / decrementing it properly but not doing termination properly & not initializing it properly.

i <= 0 in this case, i will be zero only when all content of your array already got iterated. So this loop will get terminated at first run itself. You might need to do --if you need to do reverse iteration :

for (int i = arr.length-1; i >= 0; i--) {

        System.out.println(arr[i]);
 }

Note: Array will start from zero index, so please always consider int i = arr.length-1 if you want to reverse.

  • Related