Alternate between operations in a for-loop

Viewed 4203

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 + " ");
        }
    }
 }
12 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 + " ");        
}

I don't think the OP actually wanted somebody to do their homework for them, so I'm gonna stick to answering the question they actually asked: how to alternate between two operations within a loop (so they can keep the algorithm they came up with :)).

There's a nifty "trick" that's very often used when we want to do something every other iteration in most programming languages. You'll most definitely come across it in your life, and it could be perplexing if you've got no clue what's going on, so here it goes!


The modulo (%) operator will yield the remainder of the division between its operands.

For instance, consider the following: 7 ÷ 2 = 3.5

When working for integers, you'd say that 7 ÷ 2 = 3, then you're left with 1.
In this case, when all variables are ints, in Java, 7 / 2 would be 3 and 7 % 2 is 1.

That's modulo for you!


What's interesting about this operator is inherent to what's interesting about division in general, and one case in particular: the remainder of a division by 2 is always either 0 or 1... and it alternates! That's the key word here.

Here comes the "trick" (not really a trick, it's basically a pattern considering how widely used it is) to alternating operations over iterations:

  1. take any variable that is incremented every iteration in a loop
  2. test for the remainder of the division of that variable by 2
  3. if it's 0, do something, otherwise (it'll be 1), take the alternate path!

In your case, to answer your actual question (although others do have good points, I"m not trying to take that away from anybody), you could consider using something like that:

if( i % 2 == 0 ) {
    // i is even, subtract
} else {
    // i is odd, add
}

That'd allow you to keep going with the algorithm you initially thought of!

public class exercise7 {
    public static void main(String[] args) {

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

Or you can do it this way, if you want to be a wiseass ;)

for(int i = 0, arr[] = {10,0,9,1,8,2,7,3,6,4,5,5}; i < arr.length; i++) {
    System.out.print(arr[i] + " ");
}

replace i >= 0 with i >= 5

add this : System.out.print((10-i--) + " ");

starting from what you did

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

Somethings don't need overthinking:

public class Answer2 {


    public static void main(String[] args) {

        for (int i = 0; i <= 5; i++){
            System.out.println(i);
            System.out.println(10 - i);
        }
    }
}

edit

You CAN and should generalize your task. Here is an example how you could do it (I won't write the method, since it's your job - instead I'll alter my answer just to show you the possibilities)

public class Answer2 {

    private static final Random RANDOM = new Random();

    public static void main(String[] args) {

        //You can use any upper bound for 'someLength'
        int someLength = 1 + RANDOM.nextInt(20);

        for (int i = 0; i <= someLength / 2; i++) {
            System.out.println(someLength - i);
            System.out.println(i);
        }
    }
}

This looks a bit like a homework assignment, so I won't give you working code.

But remember that you can put multiple print statements inside the for loop. You don't necessarily have to iterate 10 times to get your output. 5 times is totally enough. And as already stated in a comment above: the numbers alternate between i and 10-i, for the right range of i.

Who said that you can only use one System.out.print in the loop?

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

You should think about generalizing the series. As you have observed, the series alternates between addition and subtraction. Also, the difference goes down by one at each step. You can define variables for these two and adjust them in the loop.

    public static void main(String[] args) {
        int term = 10;
        int sign = 1;
        for(int delta = 10; delta >= -1; delta--) {
            System.out.print(term + " ");
            sign = -1 * sign;
            term = term + sign * delta;
        }
    }

I tried this code. It worked for me.

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

Simply run a loop either starting from 0 or starting from 10.

1. If you start from 10

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

2. If you start from 0

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

The output will be: 10 0 9 1 8 2 7 3 6 4 5 5

This is here. The output list is a list of combinations to make 10; 10 0 9 1 8 2 7 3 6 4 5 5

10 + 0 = 10

9 + 1 = 10

8 + 2 = 10

7 + 3 = 10

6 + 4 = 10

5 + 5 = 10

int n = 10;
int half = n / 2;
if(n % 2 == 1){
    half++;
}        
for(int x = n; x >= half;x--){
    int remainder = n % x;

    if(remainder == 0){
        remainder =  n - x;
    }
    System.out.print(x);
    System.out.print(" ");
    System.out.println(remainder);
}
Related