Right-Aligned Number Triangle

Last Updated : 11 Mar, 2026

Given an integer N, print the pattern shown below.

Examples:

Input: N = 3

Output:

3

Input: N = 6

Output:

1
Try It Yourself
redirect icon

Using Nested Loops - O(n^2) Time and O(1) Space

  • The pattern forms a right-angled triangle of numbers.
  • In each row, numbers start from 1 and go up to the row number.
  • Use an outer loop to handle the rows from 1 to N.
  • For each row, use an inner loop to print numbers from 1 to the current row index, then move to the next line.
C++
#include <iostream>
using namespace std;

// Function to print the pattern
void printPattern(int N) {
    // Loop for rows
    for (int i = 1; i <= N; i++) {        

        // Print numbers from 1 to i
        for (int j = 1; j <= i; j++) {   
            cout << j << " ";
        }
        
        // Move to next line
        cout << endl;                    
    }
}

int main() {
    int N = 5;
    
    // Call the function
    printPattern(N);

    return 0;
}
Java
public class GfG{
    
    // Function to print the pattern
    public static void printPattern(int N) {
        
        // Loop for rows
        for (int i = 1; i <= N; i++) {
            
            // Print numbers from 1 to i
            for (int j = 1; j <= i; j++) {   
                System.out.print(j + " ");
            }
            
            // Move to next line
            System.out.println();
        }
    }

    public static void main(String[] args) {
        int N = 5;
        
        // Call the function
        printPattern(N);
    }
}
Python
def print_pattern(N):
    
    # Loop for rows
    for i in range(1, N + 1): 
        
        # Print numbers from 1 to i
        for j in range(1, i + 1):   
            print(j, end=' ')
            
        # Move to next line
        print()

if __name__ == '__main__':
    N = 5
    
    # Call the function
    print_pattern(N)
C#
using System;

class GfG{
    
    // Function to print the pattern
    static void PrintPattern(int N) {
        
        // Loop for rows
        for (int i = 1; i <= N; i++) {   
            
            // Print numbers from 1 to i
            for (int j = 1; j <= i; j++) {   
                Console.Write(j + " ");
            }
            
            // Move to next line
            Console.WriteLine();
        }
    }

    static void Main() {
        int N = 5;
        
        // Call the function
        PrintPattern(N);
    }
}
JavaScript
function printPattern(N) {
    
    // Loop for rows
    for (let i = 1; i <= N; i++) {  
        
        // Print numbers from 1 to i
        let line = '';
        for (let j = 1; j <= i; j++) {   
            line += j + ' ';
        }
        
        // Move to next line
        console.log(line);
    }
}

// Call the function
printPattern(5);

Output
1 
1 2 
1 2 3 
1 2 3 4 
1 2 3 4 5 
Comment