Approach:
1. Get the number of input rows from the user using Scanner Class or BufferedReader Class object.
2. Now run two loops
- Outer loop to iterate through a number of rows as initialized or input is taken from reader class object in java. Now,
- Run an inner loop from 1 to ‘i-1’
- Ru another inner loop from 1 to rows * 2 – (i × 2 – 1)
Illustration:
Input: number = 7
Output:
*************
***********
*********
*******
*****
***
*
Methods: We can print a reverse pyramid star pattern using the following methods:
- Using while loop
- Using for loop
- Using do-while loop
Example 1: Using While Loop
Java
import java.io.*;
class GFG {
public static void main(String[] args)
{
int number = 7 ;
int i = number, j;
while (i > 0 ) {
j = 0 ;
while (j++ < number - i) {
System.out.print( " " );
}
j = 0 ;
while (j++ < (i * 2 ) - 1 ) {
System.out.print( "*" );
}
System.out.println();
i--;
}
}
}
|
Output
*************
***********
*********
*******
*****
***
*
Steps to solve this problem:
1. Initialize the size of the pyramid ‘number =7’ and the variables ‘i’ and ‘j’.
2. The outer loop will run through rows of the pyramid with ‘i’ starting from number and decrementing by 1 in each iteration.
3. First inner loop will start to print the gaps in each row with ‘j’ starting from ‘i’ and incrementing by 1 until it reaches number.
4. Now start second inner loop with ‘j’ starting at 1 and increment it by 1 until it reaches (2 * i – 1) to print the stars in each row.
5. Print new line to end each row, then repeat steps 3 through 5 until the outer loop ends.
Example 2: Using for Loop
Java
import java.io.*;
class GFG{
public static void main (String[] args)
{
int number = 7 ;
int i, j;
for (i = number; i >= 1 ; i--)
{
for (j = i; j < number; j++)
{
System.out.print( " " );
}
for (j = 1 ; j <= ( 2 * i - 1 ); j++)
{
System.out.print( "*" );
}
System.out.println( "" );
}
}
}
|
Output
*************
***********
*********
*******
*****
***
*
Example 3: Using do-while Loop
Java
import java.io.*;
public class GFG {
public static void main(String[] args)
{
int number = 7 ;
int i = number, j;
do {
j = 0 ;
do {
System.out.print( " " );
} while (j++ < number - i);
j = 0 ;
do {
System.out.print( "*" );
}
while (j++ < i * 2 - 2 );
System.out.println( "" );
}
while (--i > 0 );
}
}
|
Output
*************
***********
*********
*******
*****
***
*
Complexity Analysis :
Time Complexity : O(N^2)
Space Complexity : 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 :
20 Mar, 2023
Like Article
Save Article