Loop front and back in one line

Viewed 962

I think this is an interesting question. We can loop in one way but can we loop it backwards in the same line? Let me explain what I mean. Here is an example code:

for(int i = 0; i < 5; i++) { // we all know the output will be 0,1,2,3,4

I am looking if there is any workaround so that the above statement can print 0,1,2,3,4,3,2,1,0?

9 Answers
for (int i = -4; i <= 4; i++) {
    System.out.println(4 - Math.abs(i));
}

You can also check this out :

int a=1;
for(int i=0 ; i>-1 ; i+=a){
if (i==4)a=-a;
System.out.print(i +" ");
}

output :

0 1 2 3 4 3 2 1 0

All the logic in one line as the OP asked

  for(int i=0, d=1; i>=0 ;d=(i==4?-1:d), i+=d){
    System.out.print(i +" ");
  }

With a little bit of arithmetic, you can:

for (int i = 0; i < 9; i++) {
    System.out.println(4 - Math.abs(4 - i));
}

But simply using two for loops is easier to write and read.

Here you go

public class Main {
    public static void main(String[] args) {
        for (int i = 0, j = 8; i < 5 || j >= 0; i++, j--) {
            System.out.print((i < 5 ? i : j) + " ");
        }
    }
}

Output:

0 1 2 3 4 3 2 1 0 
for(int i = 0; i < 9; i++){
     int j = i;
     if(i >= 5)
         j = 8 - i;
     System.out.println(j);
}

There is no really simple way of doing this, but with a few modifications you can end up with a loop that can change direction:

for(int i = 0, direction = 1; 0 <= i && i < 5; direction = (i == 5-1) ? -direction : direction, i += direction)
    System.out.println(i);

In Java (generic, doesn't have to be between 0 and N):

public static void forwardAndBack(int min, int max) {
  for (int i = 0; i < (max - min + 0.5) * 2; i++) {
    System.out.println((min + i) > max ? max - (min + i - max) : min + i);
  }
}
forwardAndBack(1, 4);

In JavaScipt (just so you can see live demo):

function forwardAndBack(min, max) {
  for (let i = 0; i < (max - min + 0.5) * 2; i++) {
    console.log(min + i > max ? max - (min + i - max) : min + i);
  }
}
forwardAndBack(1, 4);
.as-console-wrapper { max-height: 100% !important; top: 0; }

A generic one liner, all the logic is in the for expressions.

int start = 0;
int max = 4;
  for(int n= start, asc = start, desc = max * 2 - start;  
       (n = asc < desc ? asc: desc) >= start ; 
       asc++, desc--)
       {
          System.out.print(n+ " ");
       }
Related