Node.js program to print a star pattern by receiving user input

Here’s a Node.js program that takes user input to print a star pattern. We will prompt the user to enter the number of rows they want in the pattern and then generate the pattern accordingly.

const readline = require('readline');

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

function printPattern(rows) {
  for (let i = 1; i <= rows; i++) {
    let pattern = '';
    for (let j = 1; j <= i; j++) {
      pattern += '* ';
    }
    console.log(pattern);
  }
}

rl.question('Enter the number of rows for the star pattern: ', (rows) => {
  const numberOfRows = parseInt(rows);

  if (isNaN(numberOfRows) || numberOfRows <= 0) {
    console.log('Invalid input. Please enter a positive number.');
  } else {
    printPattern(numberOfRows);
  }

  rl.close();
});

When you run this program, it will prompt you to enter the number of rows for the star pattern. After you enter a valid positive number, it will generate and display the pattern accordingly.

See the below screenshot:

Leave a Comment

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

Scroll to Top