Login Register Appointment

Left Align (row number) Triangle Pattern

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

Pattern:


1

22

333

4444


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 (total row=4) 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 (row=0 to total_row)

Inner loop for the columns(col= 0 to row ).

3)In each iteration of the outer loop, the inner loop prints (row+1) 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_row = 3;


        // Outer loop for rows

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

            // Inner loop for columns

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

                System.out.print(row+1);

            }

            // Move to the next line

            System.out.println();

        }

    }

}




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

int main() {

    int total_row = 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; col++) {

            cout << row+1;

        }

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

    }


    return 0;

}



Python

total_rows = 4  # number of rows



# Outer loop for rows

for row in range(total_rows):

    # Inner loop for columns

    for col in range(row):

        print(row+1, end="")  # Print stars in the same line

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