How to Make Pyramid Pattern Program in Java

08:57

Whenever we talk about logic based programs in any programming language then, number pattern and asterisk(*) pattern programs are usually asked. At student level programming i also recommends these type of programs because, these pattern type of programs will clear your basic how you should think while solving real world problems.

Here i'll talk about one of those pattern type programs that is pyramid pattern program specifically in java programming language. Pyramid pattern program is usually asked by teachers to there geek students. So, i think all students while learning any programming language should understand these pattern based programs.

No talks now come to the point.

Pyramid pattern with star as value shown in pyramid (This code is written java programming language but you can grab logic from this program and can implement in any programming language)

public class PyramidStar
{
     public static void main(String[] args)
     {
       int numRow = 5; // you can take this value by user also
       for(int i=0;i<numRow;i++) {
           // This loop will iterate how many spaces a line need
           for(int j=0;j<numRow-i;j++) { 
             System.out.print(" ");
           }
           // This loop will iterate how many stars (*) used in a line

           for(int k=0;k<=i;k++) {  
              System.out.print("* ");
           }
           System.out.println();
        }
      }
}
Pyramid pattern with number as value shown in pyramid.

public class PyramidNumber
{
  
  public static void main(String[] args)
  {
    int numRow = 5; // you can take this value by user also
    for(int i=0;i<numRow;i++) {
      // This loop will iterate how many spaces a line need
      for(int j=0;j<numRow-i;j++) { 
       System.out.print(" ");
      }
      // This loop will iterate how many number and which number used in a line

      for(int k=1;k<=i+1;k++) {  
       System.out.print(k+" ");
      }
      System.out.println();
    }
  }
}
Output of both programs: Pyramid with stars:
Pyramid with numbers:
Here you get the programs, now you can learn these logic and can implement your own logic by understanding these, but if you have any problem in understanding these or you have any other topic not understandable you can post down in comments.
Thanx by reading my post.... share this to support me for more articles like these.

You Might Also Like

2 comments

  1. Please revise the code for your first program. The value of numRow variable is not decreasing so everytime 4 blank spaces are being printed at the beginning of each line.

    ReplyDelete
    Replies
    1. 4 blank spaces are not being printed each line because at each iteration of first for loop value of i is increasing then second loop will always decreasing its iteration

      Delete

If you have any questions or suggestions, you are free to ask, i will appreciate that and, i will try my best...

Google Ads