Login Register Appointment

Left Align (col number) Triangle Pattern

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

Pattern:


1

12

123

1234


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 total 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 (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 (col+1)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_row= 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(col+1);

            }

            // Move to the next line

            System.out.println();

        }

    }

}




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_row; row++) {

            // Inner loop for columns

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

cout<<col+1;

            }

            

        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(j+1, end="")  # Print stars in the same line

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