Java Program to Print Pyramid Pattern of Stars

  • How to print a pyramid pattern of star(*) character in Java.

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
Java Program to Print Inverted Pyramid Pattern of Stars
Java Program to Print Pascal Triangle
Java Program to Print Right Triangle Star Pattern
Java Program to Print Inverted Right Triangle Star Pattern
Java Program to Print Diamond Pattern of Star Character
Java program to Print Square Pattern of Star Character
Java Program to Print Multiplication Table Triangle Pattern
Java Program to Find Length of a String
Java Program to Copy a String
Java Program to Concatenate Two Strings
Java Program to Delete a Word from Sentence
All Java Programs