Login Register Appointment

Left Align (*) Triangle Pattern

Lesson 2/21 | Study Time: 15 Min
Course: Pattern Program

Pattern:


*

**

***

****


Solution

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


Approach

1)Require minimum 2 nested loop

2)Outer loop is for row 

3)Inner loop is for column

4)Print in inner loop


Explanation:

1)The Pattern has 4 rows and each row corresponds to the row number (row 1 has 1 star, row 2 has 2 stars, etc.).

2)To print this pattern , we need two loops:

Outer loop for the rows

Inner loop for the columns(0 to row number).

3)In each iteration of the outer loop, the inner loop prints stars corresponding to the row number.


Video Solution



Java

public class Pattern {

    public static void main(String[] args) {

        // Number of rows in the pattern

        int total_rows = 3;


        // Outer loop for rows

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

            // Inner loop for columns

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

                System.out.print("*");

            }

            // Move to the next line

            System.out.println();

        }

    }

}




C++
#include <iostream>
using namespace std;

int main() {

    int rows = 4;  // number of rows


    // Outer loop for rows

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

            // Inner loop for columns

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

                cout<<"*";

            }

        cout << endl;  // Move to the next line after printing a row

    }


    return 0;

}



Python

rows = 4  # number of rows



# Outer loop for rows

for i in range(rows):

    # Inner loop for columns

    for j in range(i):

        print("*", end="")  # Print stars in the same line

    print()  # Move to the next line after printing a row