In: Computer Science
Code programs using ReadlineSync for prompts.
Note: For all programs, create and call a main function, and if required additional functions called by the main. Also please use the ES6 style of keywords => instead of the older function and for local scope variables use the keyword let, not var
triangle.js
Write a program that is required to use nested loops to generate a triangle as shown in the sample run below. The program should begin by prompting the user to enter the number of lines in the triangle and output to the console to match the example below.
Hint: Each line will contain either "O" or " " (spaces) to align the output to appear right justified
How many lines of the triangle?:6
OOOOOO
OOOOO
OOOO
OOO
OO
O
//create a folder and open a command prompt in that location
//npm install readline-sync
//type the above command to install readline-syncc
//--------- triangle.js -------
//es6 style function
//store the function in printPattern to call.
printPattern = (num)=>
{
//using let instead of var.
//from i = num down to 0
for(let i = num;i>0;i--)
{
//line variable to store the result
//console.log() will print data in logs.
//we can't print the pattern side by side.
//so use a string variable to store the patter for that
//particular line.
let line = "";
//number of O's in line
//add the i number of O's to the line.
for(let j = 1;j<=i;j++)
{
//add O to the line.
line += "O";
}
//log the line.
console.log(line);
}
}
//main function.
main = ()=>
{
//declare readline
let readline = require("readline-sync");
//read input from user.
let num = readline.question("enter the number of lines in the triangle: ");
//print the pattern by calling the function.
printPattern(num);
}
//call the main function.
main();
//please like the answer.
/*
-------------- OUTPUT ------------
C:\Users\Triangle>node triangle.js
enter the number of lines in the triangle: 6
OOOOOO
OOOOO
OOOO
OOO
OO
O
C:\Users\Triangle>node triangle.js
enter the number of lines in the triangle: sd
C:\Users\Triangle>node triangle.js
enter the number of lines in the triangle: 7
OOOOOOO
OOOOOO
OOOOO
OOOO
OOO
OO
O
*/