Open In App

Java Program to Print Reverse Pyramid Star Pattern

Last Updated : 20 Mar, 2023
Comments
Improve
Suggest changes
6 Likes
Like
Report

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:

  1. Using while loop
  2. Using for loop
  3. Using do-while loop

Example 1: Using While Loop


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


Output
*************
 ***********
  *********
   *******
    *****
     ***
      *

Example 3: Using do-while Loop


Output
 *************
  ***********
   *********
    *******
     *****
      ***
       *

Complexity Analysis :

Time Complexity : O(N^2)

Space Complexity : O(1)


Inverted Triangle
Visit Course explore course icon
Next Article
Article Tags :
Practice Tags :

Similar Reads