Mona Shahine Mona Shahine - 4 months ago 14
Java Question

Drawing a pyramid of stars

I need to write a program that will print the following output

*
* * *
* * * *


but my code till now is printing instead this

*
* *
* * *


My code is:

public class Pyramid2 {

public static void main(String[] args) {
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4 - i; j++) {
System.out.print(" ");
}

for (int k = 0; k < i; k++) {
System.out.print("* ");
}
System.out.println();
}
}
}

Answer

Looks little weird, but just do not run the loop for value of i = 1, ideally pyramid is always 1, 2 , 3... so on structure type...

public static void main(String[] args) {

        for (int i = 0 ; i < 4 ; i++) {
            if (i != 1) {
                for (int j = 0 ; j < 4 - i ; j++) {
                    System.out.print(" ");
                }
                for (int k = 0 ; k <= i ; k++) {
                    System.out.print("* ");
                }
                System.out.println();
            }
        }
    }

Output

    * 
  * * * 
 * * * *