If you are searching for a code to print a pyramid in java to complete your assignment of school or college, you are on the right place to learn more about printing pyramid using Java code & to complete your assignment.

Pyramid Triangle pattern programs in Java with explanation.png

1. Printing Simple Pyramid in Java

You can print Pyramid pattern of stars or numbers using loops and print methods in Java. There are two print method you need to know, System.out.print() and System.out.println(), the difference between print() and println() is that println adds a new line character at the end i.e. it appends \n automatically.

Code for implementing simple right angle pyramid would be

import java.io.*;

// Java code to demonstrate star pyramid pattern
public class JavaWithQAWithExperts
{
	// Function to demonstrate printing pattern
	public static void printStars(int n)
	{
                //Declare two vairables
		int i, j;

		// outer loop to handle number of rows
		// n in this case, you can provide static values like 5 for printing 5 rows
		for(i=0; i<n; i++)
		{

			// inner loop to handle number of columns			
			for(j=0; j<=i; j++)
			{
				// printing stars
				System.out.print("* ");
			}

			// just to break line, after loop for each row is completed
			System.out.println(); 
		}
}

	// Main function
	public static void main(String args[])
	{
		int n = 5;
                //Call the printStars function by passing integer value, here it is 5
		printStars(n);
	}
}

Output of the above code will be

* 
* * 
* * * 
* * * * 
* * * * *

Notes

As you can see i have already explained the above code with comments in each line, but here i am going to tell you important point of the above program.

When we are creating a pyramid, we need to need two loops( easy way, we can do it with one loop also), one for printing the "*" or you can say numbers, another to start loop again for next row(once first loop is over, call the outer loop to print next line). So, basically

2. Printing rotated Right angle triangle in Java

Now, this time we will rotate the above triangle to print rotated right angle triangle

public class JavaWithQAWithExperts
{
    // Function to demonstrate printing pattern
    public static void printStars(int n)
    {
        // declare int variable, here k is to include number of space
        int i, j, k=2*n-2;
 
        // outer loop to handle number of rows     
        for(i=0; i<n; i++)
        {
 
            // inner loop to handle number spaces
            for(j=0; j<k; j++)
            {
                // printing spaces first
                System.out.print(" ");
            }
             
            // decrementing k after each loop
            k = k - 2;
             
            //  inner loop to handle number of columns
            //  values changing acc. to outer loop
            for(j=0; j<=i; j++)
            {
                // printing stars
                System.out.print("* ");
            }
             
            // print new line for next row
            System.out.println();
        }
    }
 
    // Main Function
    public static void main(String args[])
    {
        int n = 5;
     //Call printStars with to print pyramid with 5 rows
        printStars(n);
    }
}

Output:

        *
      * * 
    * * * 
  * * * * 
* * * * * 

Notes:

As you can see in the above code we have added new variable "k", it is used to add space in the row, while printing when is executing, on first row we need 4 spaces then  * to create a pattern(when n =5, means 5 rows) so value of  k will be 2*n-2 , so k =8 for the first loop, that means we are adding 8 spaces first then printing *

For second row k =6 as  we are decrementing value of k in code

	k = k - 2;

3. Printing Triangle in JAVA

In this program, we will print equilateral triangle using java, here is the code for it

import java.io.*;

// Java code to demonstrate star pattern
public class JavaWithQAWithExperts
{
	//Main function to print triangle
	public static void printTriangle(int n)
	{
		// k= number of spaces
		int k = 2*n - 2,i,j;

		// outer loop to handle number of rows
		
		for (i=0; i<n; i++)
		{

			// inner loop to handle number spaces
			// values changing acc. to requirement
			for (j=0; j<k; j++)
			{
				// printing spaces
				System.out.print(" ");
			}

			// decrementing k after each loop
			k = k - 1;

			// inner loop to handle number of columns
			
			for (j=0; j<=i; j++ )
			{
				// printing stars
				System.out.print("* ");
			}

			// ending line after each row
			System.out.println();
		}
	}
	
	// Calling Function
	public static void main(String args[])
	{
		int n = 5; //number of rows
                 //call function to print triangle
		printTriagle(n);
	}
}

Output:

        * 
       * * 
      * * * 
     * * * * 
    * * * * * 

Note:

In the above code, again we are using K variable to print spaces but this time we are decrementing it by 1,i.e, k= k-1 , after each loop of printing spaces get's over, so basically logic is same as per the 2nd code, but changing it a little bit it generates equivalent triangle.

4. Reverse (Invert) Pyramid Triangle Program in Java

Now, let's create inverted pyramid in java, in the below we are using same logic as of in 3rd pattern but now what we need to do start the loop from number of rows instead of 1, previously we were starting loop from 1 then go on for 2...& so on, but now suppose you need 6 rows pattern, start the loop from 6th row then print 5th row, then print 4th row etc.

So here is the code

import java.io.*;

// Java code to demonstrate star pattern
public class JavaWithQAWithExperts
{
	// Function to print inverted triangle pattern
	public static void printNums(int n)
	{
		// initialising starting number
		int i, star, rows=n, space;
		
		// outer loop to handle number of rows
		// n in this case
	     for(i = rows;i >= 1; i--) {
            // Printing spaces 
            for(space = 0; space <= rows-i; space++) {
                System.out.print(" ");
            }
            // Printing stars
            star = 0;
            while(star != (2*i - 1)) {
        
                System.out.print("*");
                star++;
            }
            System.out.print("\n");
        }
	}
	
	// Driver Function
	public static void main(String args[])
	{
		int n = 5;
		printNums(n);
	}
}

Output:

 *********
  *******
   *****
    ***
     *

Note:

Take a look at the output of the code, in 5 rows pattern we are printing 9 Stars in first row, because of this code

           while(star != (2*i - 1)) { // 2*5 -1 = 9 here for first row
                System.out.print("*"); //print a star
                star++; // increase star value, as star = 0, then 1, then 2 ...so on, until 9
            }

Then again after printing for each row, we make star=0; but this time i =4, as we are decreasing row count now in the inverted pattern, so (2*i -1) = 7, above code will print 7 times star ("*") and it continues like this for 5 loops.

5. Printing pascal pattern triangle in Java

pascal-triangle-pattern-java-new.gif

To print the pascal pattern in java, let's understand the basics of the above pattern first:

  • Each number present in row is sum of the left & right number in the above row
  • If there is no number in number in above, number is assumed as 0 in java
  • First and last number in row is always 1.
  • Sum of numbers in each row is equal to sum of numbers in above row, example : 3rd rows 1+2 =3, which you can see in the 4th row.

Now we have go the basic understanding of the pattern and let's create the java code for it.

 import java.util.Scanner;

// Java code to demonstrate pascal triangle pattern
public class Main
{
	public static void main(String[] args) {
           // create a scanner class instance
           Scanner scanner = new Scanner(System.in);
           
           //ask ther user about number of rows
           System.out.print("Enter number of rows in Pascal's triangle : ");
           
           //get the number of row
           int rows = scanner.nextInt();
           
           int nextNumber;
           System.out.println("");
 
           for (int i = 0; i < rows; i++) {
                  nextNumber = 1;
                  
                  for(int k=0; k<(rows-i)*2; k++)   //create (rows-i)*2  spaces, for initial spacing.
                        System.out.print(" ");
                  
                  for (int j = 0; j <= i; j++) {
                        System.out.format("%4d", nextNumber); // %4d creates 4 space between number.
                        nextNumber = nextNumber * (i - j) / (j + 1);
                  }
                  System.out.println();
           }
    }
}

Output:

Enter number of rows in Pascal's triangle : 7

                 1
               1   1
             1   2   1
           1   3   3   1
         1   4   6   4   1
       1   5  10  10   5   1
     1   6  15  20  15   6   1

That's it, hope you have understood the concepts of looping in java, feel free to post your comments on this article.