* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
public class StarPattern18
{
public static void main(String[] args)
{
int n = 4;
// Upper half of the pattern
for(int i=1; i<=n; i++)
{
// Left stars
for (int j=1; j<=n-i+1; j++)
{
System.out.print("* ");
}
// Spaces in between
for(int j=1; j<2*(i-1); j++)
{
System.out.print(" ");
}
// Right stars
for(int j=1; j<=n-i+1; j++)
{
if (i==1 && j==n) // Avoid duplicate stars in the first row
continue;
System.out.print("* ");
}
System.out.println();
}
// Lower half of the pattern
for(int i=n-1; i>=1; i--)
{
// Left stars
for(int j=1; j<=n-i+1; j++)
{
System.out.print("* ");
}
// Spaces in between
for(int j=1; j<2*(i-1); j++)
{
System.out.print(" ");
}
// Right stars
for(int j=1; j<=n-i+1; j++)
{
if (i == 1 && j == n) // Avoid duplicate stars in the last row
continue;
System.out.print("* ");
}
System.out.println();
}
}
}
Your feedback helps us grow! If there's anything we can fix or improve, please let us know.
Weโre here to make our tutorials better based on your thoughts and suggestions.