Saturday, February 28, 2015

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

10:16 PM

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:





0 comments :

Post a Comment

 

© 2014 DieHardTechy . All rights resevered. Designed by Diehardtechy