user2141311
user2141311

Reputation: 61

Reversing Java For Loop

I have this code, which I am trying to print the following shape out...

****
* *
**
*

Current Code:

  System.out.print("\nEnter number of rows: ");
  rows = kybd.nextInt();
  for (int i = 0; i < rows; i++) {
      System.out.print("*");
  }
  for (int i = 0; i < rows; i++) {
      for (int j = 1; j <= i; j++) {
          if (j == 1 || j == rows - 1 || j == i) {
              System.out.print("*");
          } else {
              System.out.print("0");
          }
      }
      System.out.println();
  }

For some reason, it prints out like this:

****
*
**
* *

Any idea how to reverse the second for loop, so it prints the other way?

Upvotes: 0

Views: 183

Answers (3)

Juli&#225;n Urbano
Juli&#225;n Urbano

Reputation: 8488

Try this:

    Scanner kybd = new Scanner(System.in);
    System.out.print("\nEnter number of rows: ");
    int rows = kybd.nextInt();

    if (rows > 1) {
        for (int i = 0; i < rows; i++)
            System.out.print("*");
        System.out.println();

        for (int i = rows - 1; i > 1; i--) {
            System.out.print("*");
            for (int j = 2; j < i; j++)
                System.out.print(" ");
            System.out.println("*");
        }
    }
    System.out.println("*");

Sample output:

Enter number of rows: 6
******
*   *
*  *
* *
**
*

Upvotes: 1

Dinesh
Dinesh

Reputation: 2204

I feel you should change your i loop

for (int i = rows - 1; i > 0 ; i--)

Upvotes: 3

Warlord
Warlord

Reputation: 2826

Notice, that you are printing out the first line of asterisk in a separate cycle, not inside the main one. If you want to follow this road, you need to put the first cycle behind the second one.

for (int i = 0; i < rows; i++) {
    for (int j = 1; j <= i; j++) {
        if ((j == 1) || (j == (rows - 1)) || (j == i)) {
            System.out.print("*");
        } else {
            System.out.print("0");
        }
    }
    System.out.println();
}
for (int i = 0; i < rows; i++) {
    System.out.print("*");
}

Upvotes: 0

Related Questions