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, since printing pyramid pattern programs comes in basic step when you are learning a programming language.

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

6. Triangle number pattern programs In Java

(a) Pattern 1

In this pattern we will be printing numbers with rows count, for example, 1 will be printed 1 time, 2 will be printed 2 times and so on.

package TrianglePattern;
import java.util.Scanner;

public class numberPattern {
	public static void main(String[] args) 
    {
        Scanner sc = new Scanner(System.in);
         
        //Ask for number of rows    
        System.out.println("How many rows you want in this pattern?");        
        int rows = sc.nextInt();       // save rows count in this variable
        
        for (int i = 1; i <= rows; i++) 
        {
            for (int j = 1; j <= i; j++)
            {
            	//print i, 
            	//as i =1 in first outer loop, so it will print 1
            	//i=2 in second outer loop, so it will print 22
            	//i=3 in third outer loop, so it will print 333 
                System.out.print(i);
            }
             //print new line
            System.out.println();
        }
         
        //Close the resources
         
        sc.close();
    }
}

Output:

How many rows you want in this pattern?
6

1
22
333
4444
55555
666666

I have explained main loops of code using comments, read them to understand the output more clearly.

(b) Pattern 2

In this pattern we will be printing, triangle of simple numbers.

package TrianglePattern;
import java.util.Scanner;

public class numberPattern {
	public static void main(String[] args) 
    {
        Scanner sc = new Scanner(System.in);
         
        //Ask for number of rows    
        System.out.println("How many rows you want in this pattern?");        
        int rows = sc.nextInt();       // save rows count in this variable
        
        for (int i = 1; i <= rows; i++) 
        {
            for (int j = 1; j <= i; j++)
            {
            	//print i, 
            	//as i =1 in first outer loop, so it will print 1
            	//i=2 in second outer loop, so it will print 1,2
            	//i=3 in third outer loop, so it will print 1,2,3
                System.out.print(j);
            }
             //print new line
            System.out.println();
        }
         
        //Close the resources
         
        sc.close();
    }
}

Simple modification of "pattern 1" program, now we are printing varibale "j" instead of "i", so output will be as below

How many rows you want in this pattern?
6

1
12
123
1234
12345
123456

(c) Pattern 3

In this pattern we will be printing first "pattern 2" and then "reverse of pattern 2"

package TrianglePattern;
import java.util.Scanner;

public class numberPattern {
	public static void main(String[] args) 
    {
        Scanner sc = new Scanner(System.in);
         
        //Ask for number of rows    
        System.out.println("How many rows you want in this pattern?");        
        int rows = sc.nextInt();       // save rows count in this variable
        System.out.println();
        for (int i = 1; i <= rows; i++) 
        {
            for (int j = 1; j <= i; j++)
            {
            	//print i, 
            	//as i =1 in first outer loop, so it will print 1
            	//i=2 in second outer loop, so it will print 1,2
            	//i=3 in third outer loop, so it will print 1,2,3
                System.out.print(j);
            }
             //print new line
            System.out.println();
        }
        
     
         
        //Printing lower half of the pattern 
        // we will be making i = rows -1 , for example if total rows =6,
        // i =5 at first loop
        //i =4 in second outer loop
        for (int i = rows-1; i >= 1; i--)
        {
            for (int j = 1; j <= i; j++)
            {
            	// as j =1 and i=5, at first inner loop and outer loop
            	// it will print 1,2,3,4,5
            	// in second outer loop and inner loop
            	//it will print 1,2,3,4
            	// and so on
                System.out.print(j);
            }
             
            System.out.println();
        }
         
        //Close the resources
         
        sc.close();
    }
}

Output:

How many rows you want in this pattern?
6

1
12
123
1234
12345
123456
12345
1234
123
12
1

I have explained code in comments, please read them to understand the loops.

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

You may also like to read:

How to compara Strings in Java?

Fibonacci series program in Java (With and without recursion)

Java program to reverse a string (Different ways explained)

Leap year program in Java (multiple ways)