Hello Coders, In this Java tutorial we are going to solve the Pyramid triangle pattern using the concept of nested for loop.
Java pattern's questions are often asked in interview to check the coding skills, logic and looping concepts.
The pyramid pattern is the combination of Right Triangle Star Pattern and the Left Triangle Star Pattern.
So first let's see the concept of the right triangle then the left triangle and by combining both concept we can achieve our Pyramid Pattern.
In this pattern, we will use 2 for loop's first one for the rows and the second one for the columns so let's see the code for the following pattern.
class Right_Triangle_Star_Pattern{ public static void main(String[] args) { int i,j; //i represents rows and j represents columns for(i=1;i<=5;i++){ //The first for loop is for the rows. for(j=1;j<=i;j++){ // The second for loop is for the columns. System.out.print("*"); } //The cursor will point at next line after every successful iteration. System.out.println(); } } }
*
**
***
****
*****
In this Pattern we will use 3 for loop's first one for the rows, second for to print spaces in the columns, and last one for star's soo let's see the code for the pattern.
class Left_Triangle_Star_Pattern{ public static void main(String[] args) { int i,j,k; //i represents rows and j represents spaces in columns and k represent the star's in columns for(i=1;i<=5;i++){ // for loop for rows for(j=4;j>=i;j--){ // for loop for spaces in columns System.out.print(" "); } for(k=1;k<=i;k++){ // for loop for star's in columns System.out.print("*"); }
//throws the cursor in next line after printing each line System.out.println(); } } }
*
**
***
****
*****
Now let's see the code for the Pyramid pattern.
Same as left star pattern triangle we will be using 3 for loop's,first one for the rows , second for to print spaces in the columns, and last one for star's soo let's see the code for the pattern.
class Pyramid_pattern{ public static void main(String[] args) { int i,j,k; for(i=1;i<=5;i++){ for(j=5;j>=i;j--) { System.out.print(" "); } for(k=1;k<(i*2);k++){ System.out.print("*"); } System.out.println(); } } }
*
***
*****
*******
*********
I hope you understood the concept and code clearly, if not do comment below.
Also check out different questions on Java patterns:
Submitted by Sohail Chand Kalyani (sohailkalyani)
Download packets of source code on Coders Packet
Comments