Question

I am coding a program in my Java class and I need to print a pyramid of stars. My code reads:

    Scanner sc = new Scanner(System.in);
    System.out.print("Enter a number between 1 and 20: ");
    int value = sc.nextInt();
    System.out.println("Pattern B: ");
    for(int x = 1; x <= value; x++){
      for(int y = value; y>=x; y-- ){
           System.out.print("*");
     }
       System.out.print("\n");

      }

my result prints a line of 5 stars, then 4, 3, 2, 1 (if the user enters the number 5). What I want is to have the stars all pushed to the right. Such as:

a line of 5 stars, (space) line of 4 stars, (two spaces) line of 3 stars, (three spaces) line of 2 stars, (four spaces) line of one star

Am I making sense?

Should I introduce an if then statement, check the variable y and increment spaces accordingly? I am sorry if I am confusing you.

Was it helpful?

Solution 2

You could introduce a new for loop to print the required number of whitespace prior to printing your stars:

Scanner sc = new Scanner(System.in);
System.out.print("Enter a number between 1 and 20: ");
int value = sc.nextInt();
System.out.println("Pattern B: ");
for(int x = 1; x <= value; x++){
    for(int c = value-x; c<value; c++){
        System.out.print(" ");
    }
    for(int y = value; y>=x; y-- ){
        System.out.print("*");
    }
    System.out.print("\n");
}

OTHER TIPS

You can do one of two things:

  • Introduce another for loop inside the x for loop that will loop x times, to print x space characters, OR
  • Modify your y for loop to run from 1 through value, then add an if statement inside it to decide whether to print a space or a *.

Remember that if you want a real pyramid you'll have to skip every 2 numbers. If you chose 5, for example, and decide to print a line for every number until 0 this is the best you can do:

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

While if you skip you can get something like this:

*****
 ***
  *

Now all you need is see how far you are from your base to get the number of spaces, divide that by 2 and you have your previous and following spaces.

You can try something like this:

    int spacing;

    for(int x = 0; x < value; x=x+2){
          for(int y = value; y>x; y-- ){
               spacing = x/2;

               for(int i = 0; i < spacing; ++i)
                  System.out.print(" ");

               System.out.print("*");

               for(int i = 0; i < spacing; ++i)
                  System.out.print(" ");
           }
           System.out.print("\n");

     }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top