Host BR
Host BR

Reputation: 27

Very basic Java nested for loop issue

I'm having a hard time trying to get this code to start at 5 spaces and reduce to 0 spaces, subtracting a space every line.

public class Prob3 {

    public static void main(String[]args) {

        for (int x=1; x<=5; x++)
        {
            for (int y=5; y>=1; y--)
            {
            System.out.print(" ");
            }
        System.out.println(x);
        }
    }
}

Current output is (should be 5 spaces):

      5
      4
      3
      2
      1

I'm happy with the progress so far but I need to get something closer to this:

        1
      2
    3
  4
5

I feel like I'm pretty close

Upvotes: 0

Views: 118

Answers (3)

Rohit Jain
Rohit Jain

Reputation: 213361

Change your inner loop to:

for (int y=5; y > x; y--) 

You would notice a pattern in the number of whitespaces on each row:

  • Row 1 = 4 whitespaces
  • Row 2 = 3 whitespaces
  • Row 3 = 2 whitespaces
  • so on..

So, the pattern is, the number of whitespaces is 5 - rowNumber. In your code the outer loop denotes the rowNumber. And the inner loop should run 5 - rowNumber of times. That is why the condition should be y > rowNumber, i.e. y > x.

Upvotes: 6

donleyp
donleyp

Reputation: 320

Inner for loop expression should be:

public class Prob3 {
    public static void main(String[]args) {
        for (int x = 0; x < 5; x++) {
            for (int y = (4 - x); y > 0; y--) {
                 System.out.print(" ");
            }
            System.out.println(x + 1);
        }
    }
}

The problem was that you were starting at 5 each time. The (4-x) in the inner loop is so that the last number (5) has 0 leading spaces.

Upvotes: 0

Cacho Santa
Cacho Santa

Reputation: 6924

Change your inner loop to this:

for (int y=5; y>x; y--)

Full Code:

for (int x=1; x<=5; x++)
{
     for (int y=5; y>x; y--)
           System.out.print(" ");

     System.out.println(x);
}

Upvotes: 1

Related Questions