Home > Software design >  not able to print star pattern in given patter in nodeJS
not able to print star pattern in given patter in nodeJS

Time:05-18

I am looking to solve this problem for printing * start pattern in nodejs commandline. Here is the code I wrote in nodejs

var readlineSync = require('readline-sync');

const input = readlineSync.question('Enter a number')

for (var i = 0; i <= input; i = i 1){
  for(var j = 0; j <= i; j  ){
    console.log('*')
    
  }
  console.log()
}

The output I am getting in repl.it:


*

*
*

*
*
*

*
*
*
*

*
*
*
*
*

Output expected:


*
**
***
****
*****

CodePudding user response:

Console.log adds a new line, you have to create string and concat stars to that.

for (var i = 0; i < 5; i = i   1) {
  let star = "";
  for (var j = 0; j <= i; j  ) {
    star  = "*";
  }
  console.log(star);
}

You can also use the padEnd function to solve this.

const n = 5;
for (var i = 1; i <= n; i = i   1) {
  const stars = Array(i   1).join("*");
  stars.padEnd(n);
  console.log(stars);
}

CodePudding user response:

console.log always puts data in a new line set a string before the j loop, add to the string in that loop, then console.log that string after that loop

var readlineSync = require('readline-sync');

const input = readlineSync.question('Enter a number')

for (var i = 0; i <= input; i = i 1){
  var tempStr=""
  for(var j = 0; j <= i; j  ){
    tempStr ="*"
  }
  console.log(tempStr)
}

CodePudding user response:

here is a working solution with the classic readline, one loop and an array:

(async () => {
    const readline = require('readline');
    const rl = readline.createInterface({ input: process.stdin , output: process.stdout });

    const input = await new Promise(resolve => {
      rl.question("Enter a number ", resolve)
    })
  
  
    for (var i = 0; i <= input; i  ){
      console.log(Array(i).fill('*').join(''))
    }
})()

Explanation:

We use readline package to read the input, we use an IIFE in order to use async await capabilities and to await on user input which is resolved in the input variable thanks to await.

Then we create an array with the loop length which we fill of stars and join to create the string to console.log.

Here is another way without creating an array on each iteration:

(async () => {
    const readline = require('readline');
    const rl = readline.createInterface({ input: process.stdin , output: process.stdout });

    const input = await new Promise(resolve => {
      rl.question("Enter a number ", resolve)
    })
    const arrayToFill = []
  
    for (var i = 0; i <= input; i  ){
      arrayToFill[i] = '*'
      console.log(arrayToFill.join(''))
    }
})()

Hope that helps!

  • Related