LorrJ
LorrJ

Reputation: 41

Beginning Java: 'for' loops

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

Answers (4)

cahen
cahen

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

sonOfRa
sonOfRa

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

dave
dave

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

Andy Thomas
Andy Thomas

Reputation: 86391

You can:

  • Use an && rather than a comma: (i >= 0) && (j <= 3)
  • Use a single variable, and perform arithmetic on it in the body of the loop: System.out.println( i + "," + (3-i))

The comma operator takes two expressions, performs both of them, and returns the value of the last.

Upvotes: 1

Related Questions