AvP
AvP

Reputation: 359

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.

Upvotes: 0

Views: 1281

Answers (3)

ththt
ththt

Reputation: 1

Try this

int i=5;

do{
    int j=5;

    while(j>i){
        System.out.print("*");
        j--;
    }
    System.out.println();
    i--;

}while(i>0);

Upvotes: 0

guido
guido

Reputation: 19224

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

Upvotes: 1

Ducksauce88
Ducksauce88

Reputation: 650

You want to start with more spaces, then remove them until there is not more left. But while removing spaces, you also want to add and additional " * ". So for every space removed you will add an " * "

Upvotes: 0

Related Questions