How to print pyramid pattern in Java
Java code to create star pyramid pattern using nested loops. This is a common programming problem for beginners. The program asks the user to enter the number of rows of the pyramid.
Pyramid pattern:
*
***
*****
*******
*********
import java.util.Scanner;
public class StarPyramidPattern {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int rows, i, j, k, n;
do {
System.out.print("Number of rows (>1): ");
rows = sc.nextInt();
} while (rows <= 1);
n = 1; // number of '*' per row -> row 1 -> 1 *
for (i = 1; i <= rows; i++) { //outer loop -> number of rows
for (j = 1; j <= rows - i; j++) { // inner loop -> prints leading spaces for each row
System.out.print(" ");
}
for (k = 1; k <= n; k++) { // inner loop -> prints n * for each row
System.out.print("*");
}
n += 2; // The next row has 2 '*' more than the previous row
System.out.println();
}
}
}//pyramid pattern
No comments :
Post a Comment