Here is a java program to print a pyramid pattern of star(*) character. In Pyramid star pattern, ith row contains (i-1) space characters followed by (2*i - 1) star(*) characters. Check below mentioned pyramid pattern of 5 rows.
Sample Output * *** ***** ******* *********
Algorithm to print pyramid star pattern
- We first take the number of rows in the pattern as input from user and store it in a integer variable "rows".
- One iteration of outer for loop will print a row of pyramid pattern.
- There are two loops inside outer for loop. First for loop prints the spaces for every rows and following while loop prints (2*r - 1) stars for rth row of pyramid pattern.
Java Program to Print Pyramid Pattern of Star Character
package com.tcc.java.programs; import java.util.*; public class PyramidPattern { public static void main(String args[]) { int rows, i, space, star=0;; Scanner in = new Scanner(System.in); System.out.println("Enter number of rows in pattern"); rows = in.nextInt(); // printing one row in every iteration for(i = 1; i <= rows; i++) { // Printing spaces for(space = 1; space <= rows-i; space++) { System.out.print(" "); } // Printing stars while(star != (2*i - 1)) { System.out.print("*"); star++;; } star=0; // move to next row System.out.print("\n"); } } }Output
Enter number of rows in pattern 6 * *** ***** ******* ********* ***********
Recommended Posts