Login Register Appointment

Right-Aligned (1ton) Pattern

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

Pattern:


       1

     23

   456

78910 



Solution

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


Pattern Breakdown

  • The pattern has 4 rows, and each row contains stars (*) in a decreasing number:


    Row 0: 3 Space 1 number

    Row 1: 2 Space 2 number(2-3)

    Row 2: 1 Space 3 number (4-6)

    Row 3: 0 Space 4 number(7-10)


    Key observation:

    The number of spaces decreases with each row, starting from 3 (for row 0) and going down to 0 (for row 3).

    The number of digit increases with each row, starting from 1 digit (for row 0) and going up to 4 digits (for row 3).


    First Inner Loop (Spaces):

    The first inner loop prints the spaces before the number in each row.

    The number of spaces in each row is equal to total_rows - row - 1


    Second Inner Loop (Stars):

    The second inner loop prints the number in each row.(number++).

    The number of stars in each row is equal to row + 1



Video Solution


Java




public class Main {

    public static void main(String[] args) {

        int total_rows = 4;  // Number of rows

        int num = 1;  // Starting number for the sequence


        // Outer loop for rows

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

            // First inner loop for spaces

            for (int space = 0; space < total_rows - row - 1; space++) {

                System.out.print(" ");

            }

            // Second inner loop for numbers

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

                System.out.print(num);

                num++;  // Increment the number after printing

            }

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

        }

    }

}

 



C++

#include <iostream>

using namespace std;


int main() {

    int total_rows = 4;  // Number of rows

    int num = 1;  // Starting number for the sequence


    // Outer loop for rows

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

        // First inner loop for spaces

        for (int space = 0; space < total_rows - row - 1; space++) {

            cout << " ";

        }

        // Second inner loop for numbers

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

            cout << num;

            num++;  // Increment the number after printing

        }

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

    }


    return 0;

}



Python


total_rows = 4  # Number of rows

num = 1  # Starting number for the sequence


# Outer loop for rows

for row in range(total_rows):

    # First inner loop for spaces

    for space in range(total_rows - row - 1):

        print(" ", end="")

    # Second inner loop for numbers

    for numCount in range(row + 1):

        print(num, end="")

        num += 1  # Increment the number after printing

    print()  # Move to the next line