Login Register Appointment

Left Align (Digit- Alphabet alternative ) Triangle Pattern

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

Pattern:

1

AA

123

AAAA


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



Pattern Breakdown

Row 1 → 1

Row 2 → AA

Row 3 → 123

Row 4 → AAAA


Observations:

1)Odd rows contain numbers (1, 123).

2)Even rows contain uppercase As (AA, AAAA).

3)The count of elements in each row corresponds to the 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++) {

            // Check if row is odd

            if (i % 2 != 0) {

                // Print numbers from 1 to row number

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

                    System.out.print(j);

                }

            } else {

                // Print 'A' row number of times

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

                    System.out.print("A");

                }

            }

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

        }

    }

}





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++) {

        // Check if row is odd

        if (i % 2 != 0) {

            // Print numbers from 1 to row number

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

                cout << j;

            }

        } else {

            // Print 'A' row number of times

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

                cout << "A";

            }

        }

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

    }

    return 0;

}



Python

rows = 4  # Number of rows

# Outer loop for rows

for i in range(1, rows + 1):

    if i % 2 != 0:

        # Print numbers from 1 to row number

        for j in range(1, i + 1):

            print(j, end="")

    else:

        # Print 'A' row number of times

        print("A" * i, end="")  # Repeat 'A' i times

    print()  # Move to the next line