In this article, we are going to learn how to print diamond shape star patterns in Java.
Illustration:
Input: number = 7
Output:
*
***
*****
*******
*********
***********
*************
***********
*********
*******
*****
***
*
Methods: When it comes to pattern printing we do opt for standard ways of printing them via loops only. We will try out different types of loops to print the same pattern.
Example 1: Using do-while Loop
Java
import java.io.*;
public class GFG {
public static void main(String[] args)
{
int number = 7 ;
int m = 1 ;
int n;
do {
n = 1 ;
do {
System.out.print( " " );
}
while (++n <= number - m + 1 );
n = 1 ;
do {
System.out.print( "*" );
}
while (++n <= m * 2 - 1 );
System.out.println();
}
while (++m <= number);
m = number - 1 ;
do {
n = 1 ;
do {
System.out.print( " " );
} while (++n <= number - m + 1 );
n = 1 ;
do {
System.out.print( "*" );
} while (++n <= m * 2 - 1 );
System.out.println();
}
while (--m > 0 );
}
}
|
Output
*
***
*****
*******
*********
***********
*************
***********
*********
*******
*****
***
*
Time complexity: O(n^2) where n is given input number
Auxiliary Space: O(1)
Example 2: Using while Loop
Java
import java.io.*;
public class GFG {
public static void main(String[] args)
{
int number = 7 ;
int m = 1 ;
int n;
while (m <= number) {
n = 1 ;
while (n++ <= number - m) {
System.out.print( " " );
}
n = 1 ;
while (n++ <= m * 2 - 1 ) {
System.out.print( "*" );
}
System.out.println();
m++;
}
m = number - 1 ;
while (m > 0 ) {
n = 1 ;
while (n++ <= number - m) {
System.out.print( " " );
}
n = 1 ;
while (n++ <= m * 2 - 1 ) {
System.out.print( "*" );
}
System.out.println();
m--;
}
}
}
|
Output
*
***
*****
*******
*********
***********
*************
***********
*********
*******
*****
***
*
Example 3: Using for Loop
Java
import java.io.*;
public class GFG {
public static void main(String[] args)
{
int number = 7 ;
int m, n;
for (m = 1 ; m <= number; m++) {
for (n = 1 ; n <= number - m; n++) {
System.out.print( " " );
}
for (n = 1 ; n <= m * 2 - 1 ; n++) {
System.out.print( "*" );
}
System.out.println();
}
for (m = number - 1 ; m > 0 ; m--) {
for (n = 1 ; n <= number - m; n++) {
System.out.print( " " );
}
for (n = 1 ; n <= m * 2 - 1 ; n++) {
System.out.print( "*" );
}
System.out.println();
}
}
}
|
Output
*
***
*****
*******
*********
***********
*************
***********
*********
*******
*****
***
*
Time Complexity : O(n2)
Auxiliary Space : O(1)
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
12 Sep, 2022
Like Article
Save Article