Tech Me More

To quench our thirst of sharing knowledge about our day to day experience & solution to techincal problems we face in our projects.

Advertise with us !
Send us an email at diehardtechy@gmail.com

Saturday, February 28, 2015

Write a Java program to print the following pattern. [Interview Question]

Write a Java program to print the following pattern.

1
3*2
4*5*6
10*9*8*7
11*12*13*14*15

Given above is a frequently asked question in interviews from Java developers.


class TrianglePattern 
{
 public static void main(String[] args) 
 {
  int n=15;
  int i=1;
  int cnt=1;
  boolean ltr=true;
  while(i<n)
  {
   String s="";
     if(ltr)
      for(int j=0;j<cnt;j++)
    s=s+(s.length()>0?"*":"")+i++;
     else
     for(int j=0;j<cnt;j++)
    s=i++ +(s.length()>0?"*":"")+s;
     cnt=cnt+1;
     ltr=!ltr;
     System.out.println(s);
  }
  
 }
}


Output:





No comments: