Search code examples
javascriptloopsfor-loopnested-loopspseudocode

nested loop pattern add some strings


can everyone help me to find pseudocode of this code, because I want to output of the code :

1****
12***
123**
1234*
12345

I want to have the stars on the output without spread syntax or magic,

the below code I wrote here only print without the stars:

var num = 5;

for(var i = 1 ; i <= num ; i++){
       var str = "";
  for(var j = 1 ; j <= i ; j++){
          str += j
  };
  console.log(str)
};


Solution

  • Check the length of the str, and .repeat asterisks 5 - length times:

    var num = 5;
    for (var i = 1; i <= num; i++) {
      var str = "";
      for (var j = 1; j <= i; j++) {
        str += j
      };
      str += '*'.repeat(5 - str.length);
      console.log(str)
    };

    String.prototype.repeat is ES6, so for ancient browsers either use a polyfill or use a different method, like new Array(6).join('*');