Table of Contents
Introduction
The article here will illustrate Java Program to Print Pyramid Star Pattern containing nested loops.
Sample Code 1: Simple Pyramid Pattern
import java.io.*
//Java Code to demonstrate Pyramid star patterns
public class Demo
{
//Function to demonstrate printing pattern
public static void PyramidStar (int n)
{
int a, b;
//outer loop to handle the number of rows
//k in this case
for (a = 0; a < n; a ++)
{
//inner loop to handle the number of columns
//values changing according to the outer loop
for (b = 0; b < = a; b ++)
{
//printing stars
System.out.println (“ * ”);
}
//end line
System.out.println ();
}
}
//Driver Function
public static void main (String args [])
{
int k = 5;
PyramidStar (k);
}
}
OUTPUT
* * * * * * * * * * * * * * * * * * * * * * * * *
Sample Code 2: After 180 degrees rotation/ Mirrored Pattern
This program will print the star pyramid above but in reverse mirrored fashion
import java.io.*
//180 flipped pyramid star pattern
public class Demo
{
//function to demonstrate printing pattern
public static void FlippedPyramidStar (int k)
{
int a, b;
//1st loop
for (a = 0; a < k; a ++)
{
//nested 2nd loop
for (b = 2 * (k – a); b > = 0; b –)
{
//printing spaces
System.out.print (“ “);
}
//nested 3rd loop
for (b = 0; b < = a; b ++)
{
//printing stars
System.out.print (“ * ”);
}
//end line
System.out.println ();
}
}
//Driver Function
public static void main (String args [])
{
int k = 5;
FlippedPyramid Star (k);
}
}
OUTPUT
* * * * * * * * * * * * * * * * * * * * * * * * *
Sample Code 3: Printing Triangles
import java.io.*;
//Java Code to demonstrate star pattern
public class Demo
{
//Function to demonstrate printing pattern
public static void printTriangle (int n)
{
//outer loop to handle the number of rows
//n in this case
for (int I = 0; I < n; i++)
{
//inner loop to handle the number of spaces
//values changing according to requirements
for (int j = n = I; j > 1; j–)
{
//printing spaces
System.out.println(“ ”);
}
//inner loop to handle the number of columns
//values changing according to the outer loop
for (int j = 0; j < = I; j ++)
{
//printing stars
System.out.println (“ * “);
}
//ending line after each row
System.out.println ();
}
}
//Driver Function
public static void main (String args [])
{
int n = 5;
printTriangle (n);
}
}
OUTPUT
* * * * * * * * * * * * * * *
0 Comments