BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl

Java Program to Print Pyramid Star Pattern

By Chaitanya Singh | Filed Under: Java Examples

In this tutorial, we will write a java program to print the Pyramid star pattern. 

This is how a Pyramid star pattern looks like:

Number of rows = 6
Output: 
          *
         * *
        * * *
       * * * *
      * * * * *
     * * * * * *    

As you can see first row has one star, 2nd row has two stars and so on.

Program to print Pyramid Star Pattern

In the following program, we have three loops. The main for loop runs from 0 till the number of rows (which is 6 in this example). The purpose of this loop to print the number of rows of the pattern specified in numberOfRows.

The first inner for loop is to print the spaces in each row. Since we need one space in between stars, the total number of white spaces we need in first row are 5, in second row we need 4 white spaces before stars and so on.

The second inner for loop is to print the stars in each row. This loop is pretty simple, we are displaying one star in first row, two stars in 2nd row and so on.

public class JavaExample
{
  public static void main(String args[])
  {
    int row, column, numberOfRows = 6;
    for (row=0; row<numberOfRows; row++)
    {
      for (column=numberOfRows-row; column>1; column--)
      {
        System.out.print(" ");
      }
      for (column=0; column<=row; column++ )
      {
        System.out.print("* ");
      }
      // This is to move the cursor to new line for each row
      System.out.println();
    }
  }
}

Output:

Print Pyramid Star Pattern in Java

Related Java Programs

  1. Java Program to Print Left Triangle Star Pattern
  2. Java Program to Print Right Triangle Star Pattern
❮ Java TutorialJava Programs ❯

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Programs

  • C Programs
  • Java Programs
  • C++ Programs

Java Examples

  • Check Odd-even
  • Linear Search
  • Binary Search
  • Floyd's Triangle
  • Reverse number
  • Random Number
  • first n prime numbers
  • Disp prime Numbers
  • Check Prime number
  • Palindrome String
  • Find factorial
  • Sum of elements of Array
  • Area of rectangle
  • Area of Square
  • Area of Triangle
  • Circle

Tutorials

  • Java Tutorial
  • OOPs Concepts
  • Java String
  • Exception handling
  • Java Multithreading
  • Java I/O
  • Java Serialization
  • Java Regex
  • Java AWT
  • Java Swing
  • Java Enum
  • Java Annotations

Copyright © 2012 – 2022 BeginnersBook . Privacy Policy . Sitemap