Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternate between operations in a for-loop

Tags:

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 + " ");
        }
    }
 }
like image 404
WoeIs Avatar asked Sep 15 '18 20:09

WoeIs


1 Answers

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 + " ");        
}
like image 84
GBlodgett Avatar answered Sep 18 '22 19:09

GBlodgett