Alternate between operations in a for-loop

WoeIs :

I'm a Java beginner, please bear with me. :) I haven't learned anything like if statements and such yet, I've only learned about loops, variables, and classes. I need to write a single loop which produces the following output:

10 0 9 1 8 2 7 3 6 4 5 5

I can see from the segment, that the difference between the numbers is reduced by one, so from 10 to 0 it is subtracted 10, then from 0 to 9 it is added by 9, and it goes on alternating between adding and subtracting.

My idea was to create the loop where my variable i = 10 decreases by 1 in the loop (i--) but I'm not quite sure how to alternate between adding and subtracting in the loop?

 public class Exercise7 {
    public static void main(String[] args) {            
        for(int i = 10; i >= 0; i--) {
            System.out.print(i + " ");
        }
    }
 }
GBlodgett :

Why not have two extra variables and the increment one and decremented the other:

int y = 0;
int z = 10;
for(int i = 10; i >= 5; i--) {
      System.out.print(z + " " + y + " ");
      y++;
      z--;
}

Output:

10 0 9 1 8 2 7 3 6 4 5 5 

However we can also do this without extra variables:

for(int i = 10; i >= 5; i--) {
   System.out.print(i + " " + 10-i + " ");        
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=35333&siteId=1