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*

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

Post a Comment

Popular posts from this blog

Program to define a class 'employee' with data members as empid, name and salary. Accept data for 5 objects using Array of objects and print it.

Program to input age from user and throw user-defined exception if entered age is negative

Define a class Student with four data members such as name, roll no.,sub1, and sub2. Define appropriate methods to initialize and display the values of data members. Also calculate total marks and percentage scored by student.