user3366866
user3366866

Reputation: 19

Nested 'for' loops

Prompts the user for 2 natural numbers x and y.

Checks if those numbers are in the set of natural numbers; exits if they are not.

Prints all pairs of numbers up to (x,y).

Example:

Enter a natural number for x: 3

Enter a natural number for y: 2

(0,0),(0,1),(0,2)
(1,0),(1,1),(1,2)
(2,0),(2,1),(2,2)
(3,0),(3,1),(3,2)
There are 12 pairs.  

I know I will need to use some placement of if checks, print and println to get the output to look exactly as shown.

this is what I have so far:

Scanner scan = new Scanner (System.in);
System.out.println("Enter a natural number for x: ");
int x = scan.nextInt();
System.out.println("Enter a natural number for y: ");
int y = scan.nextInt();


if (x>0 && y>0)
{
    for (x = 0; x <= x ; x++)
    {
        for (y=0; y <= y ; y++)
        {
            System.out.println(x + " " + y);
        }
    }
}
else
{
    System.exit(0);
}

I am not sure how to go on from here, I can tell that my for loops are most likely incorrect.

Upvotes: 0

Views: 111

Answers (2)

esdebon
esdebon

Reputation: 2739

System.out.println("Enter a natural number for x: ");
int x = scan.nextInt();
System.out.println("Enter a natural number for y: ");
int y = scan.nextInt();


if (i>0 && j>0)
{
    for (i = 0; i <= x ; i++)
    {
        for (j=0; j <= y ; j++)
        {
            System.out.print("("+i + ", " + j+")");
        }
        System.out.println("");
    }

}
else
{
    System.exit(0);
}

Or

System.out.println("Enter a natural number for x: ");
int x = scan.nextInt();
System.out.println("Enter a natural number for y: ");
int y = scan.nextInt();


if (i>0 && j>0)
{
    for (i = 0; i <= x ; i++)
    {
        for (j=0; j <= y ; j++)
        {
            if(j != y){
                System.out.print("("+i + ", " + j+")");
            }else{
                System.out.println("("+i + ", " + j+")");
            }
        }

    }

}
else
{
    System.exit(0);
}

Upvotes: 1

La-comadreja
La-comadreja

Reputation: 5755

for (int i = 0; i <= x; i++) {
    for (int j = 0; j <= y; j++)
        System.out.println("(" + i + ", " + j + ")");
}

Upvotes: 1

Related Questions