Print Number Pattern In JavaScript

In this topic,

We will see print number pattern in javascript

1. Triangle pattern (1)

$(document).ready(function(){
   var i ;
   var j,text="";
   for (i =1; i <=5 ; i++) {  
      for (j = 1; j <=i ; j++) {  
        text += j;
      } 
      text  +=  "<br>";
   }
      
   $("#demo").html (text);
});

Output:

The pattern shown above is a triangle-shaped pattern using numbers. To create the above pattern run 2 nested loops, internal loop will take care of rows (number of iterations and printing pattern) while the external loop will look for a column mechanism.

Run external loop for ‘n’ a number of times from 1 to ‘n’, where ‘n’ is the height of the triangle, i.e for(let i = 0;i <= n; i++).

The internal loop will run 1 time in the first iteration of external code, 2 times in the second iteration, and so on and will add the iteration number of the internal loop to the string.

2. Triangle pattern (2)

$(document).ready(function(){
     
        var i ;
        var j,text="";
        for (i = 5; i>=1 ; i--) {  
      for (j = 1; j<=i ; j++) {  
        text += j;
      } 
      text  +=  "<br>";
    }
      
    $("#demo").html (text);
}); 

Output:

In this pattern control, an internal loop such as it runs for ‘n’ times in the 1st iteration of the external loop, ‘n – 1’ times in the 2nd iteration, and so on. To get this set initialization variable j less than 'n - i + 1'. Now use the initialization variable of the internal loop for character increment.

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories