49.9k views
2 votes
Complete the drawTriangle() function in that draws a triangle with asterisks (*) based on the size parameter.

Ex: drawTriangle(4) outputs to the console a triangle with size 4, so the longest side (4 asterisks) appears on the bottom line:
*
**
***
****

1 Answer

3 votes

Final answer:

The question requires creating a function drawTriangle() that outputs a triangle made of asterisks to the console. The function uses loops to control the number of asterisks per line, increasing with each new line to form the triangle shape.

Step-by-step explanation:

You are tasked with writing a function drawTriangle() that takes a size parameter and displays a triangle made of asterisks (*) to the console. This function is a common exercise in programming that requires you to manipulate strings and output them in a loop to create the desired pattern.

To create a triangle with the longest side (consisting of asterisks equal to the size parameter) on the bottom, you would typically use nested loops. The outer loop controls the number of lines, and the inner loop controls the number of asterisks per line.

Here's a pseudo-code example for drawTriangle(4):

function drawTriangle(size) {
for (let line = 1; line <= size; line++) {
let stars = '';
for (let starCount = 1; starCount <= line; starCount++) {
stars += '*';
}
console.log(stars);
}
}

Remember, the length or number of asterisks per line increases with each iteration, eventually forming a right-angled triangle shape on the console.

User Ondrej Kvasnovsky
by
8.8k points