How to construct a Pyramid Pattern using for loop in java?

Introduction:

Hii all, here we are going to make a pyramid pattern using for loop in java.First of all, I would like to tell pattern programming became quite easy if you analyse the pattern properly and for analysing properly you can use a notebook and pen.It’s a bit advice for all to analyse first and then move forward so that you could understand the condition well.

Description Of Program:

As I mentioned before, we construct the pattern in our notebook, then we are making our pattern using “*” this symbol so, construct the pattern first and count the stars and spaces being used in the program.Initially, we think for the upper triangle and for this we will run three loops here named (i, j & k).Loop “i” will be run for a row of the pattern then we will come inside the bracket, then “j” loop will be run for ” ” i.e. space and “k” loop will be run for ” *” this symbol.Hence, as the number of rows increases ” *” symbol increases simultaneously.Therefore, “k” runs up to “i” and  “j” will run up to “n-i” since it is used for spaces we made. Moving forward we will follow the same procedure for reverse pyramid and for this we just run the “i” loop in the opposite direction, rest procedure will be same.Hope it would help you.

CODE :

package Patterns;

import java.util.Scanner;
public class Pyramid {
public static void main(String[] args) {
Scanner s=new Scanner(System.in);

System.out.println(“Enter N”);
int n=s.nextInt();
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n-i; j++)
System.out.print(” “);
for(int k=1;k<=i;k++)
System.out.print(” *”);
System.out.println();
}
for(int i=n-1;i>=1;i–)
{
for(int j=1;j<=n-i; j++)
System.out.print(” “);
for(int k=1;k<=i;k++)
System.out.print(” *”);
System.out.println();
}
}
}

OUTPUT :

Leave a Reply