Alternate between operations in a for-loop
public class exercise7 {
public static void main(String[] args) {
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 int
s, 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:
- take any variable that is incremented every iteration in a loop
- test for the remainder of the division of that variable by
2
- if it's
0
, do something, otherwise (it'll be1
), 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!
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] + " ");
}
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 + " ");
}