Login Register Appointment

Left Align (Alphabets-column wise) Triangle Pattern

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

Pattern:


A

AB

ABC

ABCD


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.

2)The first row contains A, the second row contains AB, the third row contains ABC, and so on.

We use two loops:

Outer loop for rows (from 1 to 4).

Inner loop to print characters from 'A' to the respective row number.


Video Solution



Java

public class Main {

    public static void main(String[] args) {

        int rows = 4;  // Number of rows


        // Outer loop for rows

        for (int i = 1; i <= rows; i++) {

            // Inner loop for characters

            for (char ch = 'A'; ch < 'A' + i; ch++) {

                System.out.print(ch);

            }

            System.out.println();  // Move to the next line after printing a row

        }

    }

}




C++

#include <iostream>

using namespace std;


int main() {

    int rows = 4;  // Number of rows


    // Outer loop for rows

    for (int i = 1; i <= rows; i++) {

        // Inner loop for characters

        for (char ch = 'A'; ch < 'A' + i; ch++) {

            cout << ch;

        }

        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(1, rows + 1):

    # Inner loop for characters

    for ch in range(ord('A'), ord('A') + i):

        print(chr(ch), end="")  # Convert ASCII to character

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