20

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 + " ");
        }
    }
 }
ccjmne
  • 9,333
  • 3
  • 47
  • 62
WoeIs
  • 1,083
  • 1
  • 15
  • 25
  • Think about this: for which `i` values do you want to add and for which to subtract? – user1803551 Sep 15 '18 at 20:24
  • 8
    I like the old stand-by `System.out.println("10 0 9 1 8 2 7 3 6 4 5 5");` but I guess the instructions do say to use a loop. Hmm, maybe just loop once... – markspace Sep 15 '18 at 20:34

12 Answers12

22

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 + " ");        
}
GBlodgett
  • 12,704
  • 4
  • 31
  • 45
20

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!

ccjmne
  • 9,333
  • 3
  • 47
  • 62
  • 2
    Another way to alternate operations is to flip between 1 and -1. `i = 1` before the loop and `i = i * -1` inside the loop Or if you want to alternate between 1 and 0 do `i = (i - 1) * -1` in the loop instead This is not to be used on the index variable of a `for` loop – Ilia Gilmijarow Oct 09 '18 at 13:44
  • @IliaGilmijarow The advantage to the solution I described here is that it can be trivially changed to alternate not only between **two** options, but also _three_, _four_, or **any other number**. It's generic enough to implement any _FizzBuzz_-type routine! – ccjmne Oct 15 '18 at 15:54
  • Yes. That is true, @ccjmne. I just wanted to put another way out there. Maybe someone finds it helpful... – Ilia Gilmijarow Oct 16 '18 at 14:40
  • @IliaGilmijarow: Oh yeah, certainly! You're absolutely welcome to do so . I didn't mean to shut you up or anything, and I'm sorry that my comment came across as rude – ccjmne Oct 16 '18 at 21:00
6
public class exercise7 {
    public static void main(String[] args) {

        for(int i = 10; i >= 5; i--) {
            System.out.print(i + " " + (10-i) + " ");
        }
    }
}
Nandl66
  • 284
  • 2
  • 11
5

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] + " ");
}
Jens Roland
  • 27,450
  • 14
  • 82
  • 104
  • Why not `int[] arr = {...}; for (int a : arr) /* */ ;` :P – hyper-neutrino Sep 15 '18 at 20:32
  • 2
    @HyperNeutrino Usually it's preferred to keep the tightest possible scope on variables. Since `arr` isn't used outside of the loop, it's scope is limited to that of the loop itself. – markspace Sep 15 '18 at 20:36
5

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--) + " ");                 
          }
      }
 }
The Scientific Method
  • 2,374
  • 2
  • 14
  • 25
5

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);
        }
    }
}
Nicholas K
  • 15,148
  • 7
  • 31
  • 57
zlakad
  • 1,314
  • 1
  • 9
  • 16
5

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.

Markus
  • 3,155
  • 2
  • 23
  • 33
4

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) + " ");
}
Johannes Kuhn
  • 14,778
  • 4
  • 49
  • 73
  • 1
    good answer but interestingly enough you're still only using one `System.out.print` in the loop :P – hyper-neutrino Sep 15 '18 at 21:32
  • 1
    Yeah. First thought about using two of them, but then decided, well heck, I'm already doing string concatenation. – Johannes Kuhn Sep 16 '18 at 18:26
  • 1
    This would print `10 1 9 2 8 3 7 4 6 5`. You probably meant `i <= 5` in the loop, and `i` instead of `i+1` inside the `print()`. – walen Sep 17 '18 at 11:01
4

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;
        }
    }
chandra
  • 500
  • 4
  • 12
1

I tried this code. It worked for me.

for(int i = 10; i >= 5; i--) {
   System.out.print(i + " ");
   System.out.print(10-i + " ");
}
Abdur Rahman
  • 1,420
  • 1
  • 21
  • 32
1

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

0

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);
}
nitrodmr
  • 198
  • 2
  • 8