Login Register Appointment

Decreasing Pyramid

Lesson 19/21 | Study Time: 20 Min
Course: Pattern Program

Pattern:

 *********

 *******

  *****

   ***

    *     



Solution

Note: Don't jump directly to the solution, try it out yourself first.


Pattern Breakdown

The pattern has 4 rows, and each row contains stars (*) in a decreasing number:


Row 0: 0 Space 7 star 0 space

Row 1: 1 Space 5 star 1 space

Row 2: 2 Space 3 star 2 space

Row 3: 3 Space 1 star 3 space


Key observation:

The number of spaces increase with each row, starting from 0 (for row 0) and going down to 3 (for row 3).

The number of star decrease with each row, starting from 7 star (for row 0) and going up to 1 star(for row 3).


First Inner Loop (Spaces):

The first inner loop prints the spaces before the number in each row.

The number of spaces in each row is equal to row


Second Inner Loop (Stars):

The second inner loop prints the start in each row.

The number of stars in each row decreased by 2 for each row.

For the i-th row, the number of stars is 2 * (total_rows - i) - 1


Video Solution


Java

          public class Main {

    public static void main(String[] args) {

        int total_rows = 5;  // Total number of rows in the pyramid


        // Outer loop for rows

        for (int row = 0; row < total_rows; row++) {

            // First inner loop for spaces

            for (int space = 0; space < row; space++) {

                System.out.print(" ");

            }

            // Second inner loop for stars

            for (int star = 0; star < 2 * (total_rows - row) - 1; star++) {

                System.out.print("*");

            }

            System.out.println();  // Move to the next line

        }

    }

}


C++

#include <iostream>

using namespace std;


int main() {

    int total_rows = 5;  // Total number of rows in the pyramid


    // Outer loop for rows

    for (int row = 0; row < total_rows; row++) {

        // First inner loop for spaces

        for (int space = 0; space < row; space++) {

            cout << " ";

        }

        // Second inner loop for stars

        for (int star = 0; star < 2 * (total_rows - row) - 1; star++) {

            cout << "*";

        }

        cout << endl;  // Move to the next line

    }


    return 0;

}



Python

     

     total_rows = 5  # Total number of rows in the pyramid


# Outer loop for rows

for row in range(total_rows):

    # First inner loop for spaces

    for space in range(row):

        print(" ", end="")

    # Second inner loop for stars

    for star in range(2 * (total_rows - row) - 1):

        print("*", end="")

    print()  # Move to the next line