Reputation: 41
I want a program that prints the following: (3,0), (2,1) , (1,2) and (0,3)
But I can't get it right, see the code below. What would be the appropriate syntax to get what I want?
public class experiment1 {
public static void main(String[] args) {
for(int i = 3, int j = 0; i >= 0, j <= 3; i--, j++)
{
System.out.println(i + "\t"+ j);
}
}
}
Upvotes: 0
Views: 130
Reputation: 16636
Your solution is correct, except for the syntax error. Without changing much your code, the "for" would look like this after the fix:
for (int i = 3, j = 0; i >= 0; i--, j++)
{
System.out.println(i + "\t"+ j);
}
Upvotes: 0
Reputation: 1440
The best thing I could come up for this is using modulo.
for(int i = 0; i < 3; i++) {
System.out.println("(" + i % 3 + "," + i + "));
}
This eliminates the need for a second variable.
Upvotes: -1
Reputation: 12806
You don't need to include two variables in that loop. In general, try to avoid over-complicating code by adding extra variables / unnecessary machinery.
Try this out:
for(int i = 0; i <= 3; i++){
System.out.println((3-i) + "\t" + i);
}
Upvotes: 10
Reputation: 86391
You can:
The comma operator takes two expressions, performs both of them, and returns the value of the last.
Upvotes: 1