Lex_i
Lex_i

Reputation: 129

How to construct a pyramid in Java

How do I construct a pyramid using a loop program, given a number of rows by a user's input? Such as

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

I've tried watching several videos and reading articles about the logic of this, but instructors were either not understandable or they skipped lines of reasoning.

I know every row increases by 2 stars, and I know that because every row has an odd number of stars I can define the number of stars in a row as 2n+1 where n is an integer. I noticed a 2 row triangle has a base of 3 stars, a 3 row triangle has a base of 5 stars, and so on. So for an nth row, the triangles base is n+(n-1), which is 2n-1. For example, r_5: base = 9 stars. The next thing I know my program needs to consider is spacing. I noticed, from the base, spacing increases by 2 every row until we have n-1 spaces on the first half and another n-1 spaces on the second half, in other words, spacing increases from the base until it is greater than or equal to 2b-2.

I think all that covers the gist a java program would need to know: the number of stars per row, the size of the base, and spacing. But how do I translate all this in terms of a for while loop?

Upvotes: 2

Views: 2481

Answers (3)

Tameem Khan
Tameem Khan

Reputation: 846

Method 1

Note that, if we denote current line number as "line" starting from 0, and total number of lines as "n",

Number of stars in each line = 2*line + 1

Number of leading (or trailing) spaces in each line = n - line - 1

We can simply generate the pyramid using this rule:

int n = 4;
for (int line = 0; line < n; line++) {
    StringBuilder sb = new StringBuilder();
    int starsToAppend = 2 * line + 1;
    int spaceToAppend = n - line - 1;

    while (spaceToAppend-- > 0) sb.append(" ");
    while (starsToAppend-- > 0) sb.append("*");

    System.out.println(sb.toString());
}

Method 2

You can also approach from the middle and expand. Note that there is a constant column of a star (*) in the middle, and on each side, only one star gets added in each line each time. And the rest are spaces.

int n = 4;
for(int line=0; line <n ; line++){
    StringBuilder sb = new StringBuilder("*");
    int spacesToAppendOnBothSides = n-line-1;
    int starsToAppendOnBothSides = line;

    for(int idx=0; idx<starsToAppendOnBothSides; idx++){
        sb.insert(0, "*");  //appends to the beginning
        sb.append("*");     //appends to the end
    }
    for(int idx=0; idx<spacesToAppendOnBothSides; idx++){
        sb.insert(0, " ");
        sb.append(" "); //NOTE: You may exclude this line to avoid adding trailing spaces
    }
    System.out.println(sb.toString());
}

Explanation:

  1. On first iteration (line == 0) we take a single star,
*
  1. and add zero extra stars (as our line# is zero) on both sides, which gives us (same string):
*
  1. And then add n-line-1 (we substract 1 because we already added 1 character - the first star) = 3 spaces on each side of that star, which gives us:
...*...

On 2nd iteration (line == 1) if we apply same logic: 1.

    *
    ***
     ^ This middle one is the first star
    ..***..

Pretty simple once you understand the logic. There are multiple ways to do this, but these are among the simplest ones :)

Upvotes: 4

Ishan
Ishan

Reputation: 1006

Here's my implementation -

public static String repeat(String str, int times) {
    return new String(new char[times]).replace("\0", str);
}

public void createPyramid(int size) {
    for (int i = 1; i <= size; i += 2) {
        int numSpaces = (size - i) / 2;
        System.out.println(repeat(" ", numSpaces) + repeat("*", i) + repeat(" ", numSpaces));
    }
}

Call the method as - createPyramid(7); should give you the desired output. You can increase the size for bigger pyramid.

The variable i iterate for the size of the pyramid. And the number of stars on each row is increasing by 2 starting from 0. There i is incrementing by 2. The blank spaces will be equal to size - number of *'s but they have to be repeated before and after the *'s symmetrically, we divide it by 2. This will give the number of spaces before and after the *'s and in the middle we just need to print the *'s whose number is given by i. So, we finally print them. The repeat function creates a String formed from the str parameter repeated times times. eg - if we call repeat("abc", 3), it will return "abcabcabc".

Upvotes: -2

Maurice Perry
Maurice Perry

Reputation: 9651

Say you need to print a pyramid of n rows. You can see that row i (where i is between 1 and n) will start with n-i spaces and have (i-1)*2+1 asterisks:

    for (int i = 1; i <= n; ++i) {
        int spaces = n-i;
        int stars = (i-1)*2+1;
        for (int j = 1; j <= spaces; ++j) {
            System.out.print(' ');
        }
        for (int j = 1; j <= stars; ++j) {
            System.out.print('*');
        }
        System.out.println();
    }

Upvotes: 1

Related Questions