Search code examples
javanestednested-loops

Patterns using for loops


I am supposed to create this pattern based on the number a user enters. The number the user enters corresponds to the number of rows and stars in each row.

    * 
   ** 
  *** 
 **** 
*****

I was told to only use nested for loops and cannot use printf(). This is only part of the code that I am working on.

for (int row = 1; row <= size; row++) {
            for (int column = 1; column <row; column++) {
                System.out.print(" ");
            }
            for (int column = 1; column <= row; column++) {
            System.out.print("*");
        }
        System.out.println();

    }

I cannot seem to make my output as shown above. Instead I get this:

*
 **
  ***
   ****
    *****

Could someone give me a hint as to what I am supposed to do? I have spent 2 hours but still can't figure it out.


Solution

  • For each row, you should output maximum size characters; so if size = 5, on third row, if output three stars, then you need size-row spaces => 5 - 3 = 2.

    In code:

    for (int row = 1; row <= size; row++) {
        for (int column = 1; column <= size-row; column++) {
            System.out.print(" ");
        }
        for (int column = 1; column <= row; column++) {
            System.out.print("*");
        }
        System.out.println();
    }
    

    Sample: http://ideone.com/hC5HDQ