Wednesday, 22 February 2017

Pascal triangle 5

This program will display the pascal triangle or print star pattern as shown below:


    *
   *A*
  *A*A*
 *A*A*A*
*A*A*A*A*


In this program, there are three "for" loops are used. The first outer for loop is used for the number of lines here it is 5. The second (first inner) loop is used for printing blank spaces. And the third (second inner) loop is used for printing "*" or "A". If the value of k is odd number then we will print "*" and if the value is even number then we will print "A" as given in below program.


PROGRAM
class StarPattern {

 public static void main(String args[]) {
   for(int i=1; i<=5; i++) {  // For number of lines (here 5 line)
   
      for(int j=5-i; j>0; j--) {  
         // For blank spaces
         System.out.print(" ");
      }
      
      for(int k=1; k<=i*2-1; k++) {
         // If odd then print "*" otherwise (for even) print "A"
         if(k%2 != 0)     
             System.out.print("*");
         else
             System.out.print("A");
      }
      System.out.println("");
    }
 }
}

OUTPUT
        *
      *A*
     *A*A*
   *A*A*A*
*A*A*A*A*

2 comments:

  1. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a Java developer learn from Java Training in Chennai. or learn thru Java Online Training in India . Nowadays Java has tons of job opportunities on various vertical industry.

    ReplyDelete