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*

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.

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.

Program to design an applet which display a triangle filled with red colour and a message as "The triangle" in blue below it