How to print random Patterns in java

In this post, we will cover an important topic in java which is a pattern problem in Java. Patterns problem are mostly asked in interviews and Technical round. So we will now discuss this topic with an example pattern problem. In this problem of the pattern mostly we have used for each loop, while loop etc. Now I mention the code of the program please read and understand carefully because it’s not easy as compared to other topics.

Write a program to print the following *000*000* pattern in Java

Pattern:

*000*000*
0*00*00*0
00*0*0*00
000***000

Solution: Pattern program in java

 public class Pattern1
{    
     public static void main(String[] args){  //main function started  
    int lines=4;    
    int i,j;    
    for(i=1;i<=lines;i++){// this loop is used to print lines    
      for(j=1;j<=lines;j++){// this loop is used to print * in a line    
          if(i==j)   //compare the valu of i and j 
             System.out.print("*"); //for print the *   
            else    
           System.out.print("0"); //For print the 0   
      }    
      j--;    
       System.out.print("*");    
      while(j>=1){// this loop is used to print * in a line    
          if(i==j)    
           System.out.print("*");    
          else    
           System.out.print("0");    
          j--;    
      }    
    System.out.println("");    
  }    
         }    
}

 

Output of program

*000*000*
0*00*00*0
00*0*0*00
000***000

Also read,

In this program, we will use many loops. Each loop worked separately. In this program, i and j are integer variables I print and count the lines and J print the columns. we use nested loops for printing the patterns. The complexity of nested loops is O^2. The logic behind these patterns is the nested loop.

If anybody doesn’t understand this please do comments I will help you. If all of you learn an extra thing please go through the links which are mention below.



Leave a Reply

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