QABash Community Forum

Please or Register to create posts and topics.

ASCII art pyramid with N levels

We can render an ASCII art pyramid with N levels by printing N rows of asterisks, where the top row has a single asterisk in the center and each successive row has two additional asterisks on either side.

Here's what that looks like when N is equal to 3.

  *  
 *** 
*****

And here's what it looks like when N is equal to 5.

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

Can you write a program that generates this pyramid with a N value of 10?

  • [execution time limit] 3 seconds (java)
  • [memory limit] 2g
class Solution {
    public static void main(String[] args) {
        int N = 10; // Number of levels in the pyramid
        for (int i = 1; i <= N; i++) {
            int spaces = N - i;
            int stars = 2 * i - 1;
            // Print spaces
            for (int j = 0; j < spaces; j++) {
                System.out.print(" ");
            }
            // Print stars
            for (int j = 0; j < stars; j++) {
                System.out.print("*");
            }
            // New line after each level
            System.out.println();
        }
    }
}

 

Scroll to Top
×