How to Print a Staircase Pattern in Java

In this tutorial, we will learn how to print a Staircase pattern in Java.
A staircase can be either Left-Aligned or Right-Aligned.

A staircase is a simple java pattern program which requires the knowledge of how loops work in Java.
In this program, we use the concept of nested for-loops to print the pattern.
The outer for loop is used to iterate over the height of the staircase and the inner for loop is used to print the pattern.
When we want to print

  • Left-aligned staircase we declare the value as 1 at run time.
  • Right-aligned staircase we declare the value as 2 at run time.

 

Code to Print a staircase pattern in Java

import java.util.*;
class Staircase
{
  public static void main(String[]args)
  {
    Scanner scan = new Scanner(System.in);
    System.out.print("Enter the height of Staircase: ");
    int height = scan.nextInt();

    System.out.print("Enter 1 for Left aligned Staircase and 2 for Right aligned Staircase: ");
    int check = scan.nextInt();
    
    if(check == 1)
    {
      for(int i = 0; i < height; i++)
      {
        for(int j = 0; j < height; j++)
        {
          if(i >= j)
          {
            System.out.print("# ");
          }
        }
        System.out.println();
      }
    }
    else if(check == 2)
    {
      int c = height - 1;
        	for(int i = 0; i < height; i++)
        	{
            	for(int j = 0; j < height; j++)
            	{
                	if(j < c)
                	{
                    	System.out.print("  ");
                	}
                	else
                	{
                    	System.out.print(" #");
                	}
            	}
                System.out.println();
                c = c - 1;
        	}
    }
    else
    {
      System.out.println("Enter valid number.");
    }
  }	
}

 

Output:

Enter the height of Staircase: 5
Enter 1 for Left aligned Staircase and 2 for Right aligned Staircase: 1
# 
# # 
# # # 
# # # # 
# # # # #
Enter the height of Staircase: 3
Enter 1 for Left aligned Staircase and 2 for Right aligned Staircase: 3
Enter valid number.
Enter the height of Staircase: 8
Enter 1 for Left aligned Staircase and 2 for Right aligned Staircase: 2
               #
             # #
           # # #
         # # # #
       # # # # #
     # # # # # #
   # # # # # # #
 # # # # # # # #

 

Hope you understand the code 🙂
Any questions please feel free to drop in your comments.

You can also check:

Leave a Reply

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