Login Register Appointment

Right- Aligned (*) Pattern

Lesson 16/21 | Study Time: 15 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: 3 Space 1 stars


    Row 1: 2 Space 2 stars


    Row 2: 1 Space 3 stars


    Row 3: 0 Space 4 stars


    Key observation:
    The number of spaces decreases with each row, starting from 3 (for row 0) and going down to 0 (for row 3).
    The number of stars increases with each row, starting from 1 star (for row 0) and going up to 4 stars (for row 3).


    First Inner Loop (Spaces):

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

    The number of spaces in each row is equal to total_rows - row - 1


    Second Inner Loop (Stars):

    The second inner loop prints the stars in each row.

    The number of stars in each row is equal to row + 1



Video Solution

Java

public class Main {

    public static void main(String[] args) {

        int total_rows = 4;  // Number of rows


        // Outer loop for rows

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

            // Inner loop for spaces

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

                System.out.print(" ");

            }

            // Inner loop for stars

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

                System.out.print("*");

            }

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

        }

    }

}



C++


#include <iostream>

using namespace std;

int main() {

    int total_rows = 4;  // Number of rows


    // Outer loop for rows

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

        // Inner loop for spaces

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

            cout << " ";

        }

        // Inner loop for stars

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

            cout << "*";

        }

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

    }


    return 0;

}



Python


total_rows = 4  # Number of rows


# Outer loop for rows

for row in range(total_rows):

    # Inner loop for spaces

    for space in range(total_rows - row - 1):

        print(" ", end="")

    # Inner loop for stars

    for star in range(row + 1):

        print("*", end="")

    print()  # Move to the next line