Open In App

JavaScript Program to Print Number Pattern

Last Updated : 16 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

The idea of pattern-based programs is to understand the concept of nesting for loops and how and where to place the alphabet/numbers/stars to make the desired pattern.

These are the following approaches to printing different types of number patterns:

Approach 1: Using nested loops

In this approach Nested loops iterate through rows and columns, incrementing row count in the outer loop and column count inner loop, to print desired patterns or structures like right angled trangle.

Example: We are using nested loops to print a number pattern with increasing numbers on each line, up to the specified limit of 5.

Javascript




const n = 5;
for (let i = 1; i <= n; i++) {
    let str = '';
    for (let j = 1; j <= i; j++) {
        str += j + ' ';
    }
    console.log(str);
}


Output

1 
1 2 
1 2 3 
1 2 3 4 
1 2 3 4 5 

Approach 2: Using array manipulation and join() method

In JavaScript, an array is populated incrementally to form each line of the pattern. The join() method converts the array elements into a string, separating them with spaces. here we are creating a pyramid by using a number pattern.

Example: We are using nested loops, array manipulation, and the join() method, this JavaScript code prints a number pattern with spaces, where numbers increase along each row up to 5.

Javascript




const n = 5;
for (let i = 1; i <= n; i++) {
    let arr = [];
    let count = 1;
    for (let j = 1; j <= 2 * n; ++j) {
        if (i + j >= n + 1 && (i >= j - n + 1)) {
            arr.push(count);
            count++;
        } else {
            arr.push(' ');
        }
    }
    console.log(arr.join(' '));
}


Output

        1          
      1 2 3        
    1 2 3 4 5      
  1 2 3 4 5 6 7    
1 2 3 4 5 6 7 8 9  


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads