In this tutorial, we will learn how to print a triangle using asterisks (*) in JavaScript. This is a common exercise in programming that helps you understand loops and conditions in any programming language.
First, let’s start by creating a function that takes one parameter, which will be the number of rows of the triangle. The function will print a right-angled triangle with the specified number of rows.
function printTriangle(rows) {
// outer loop to iterate through each row
for (let i = 1; i <= rows; i++) {
// inner loop to print asterisks for each row
let asterisks = '';
for (let j = 1; j <= i; j++) {
asterisks += '*';
}
console.log(asterisks);
}
}
Now, let’s call this function with a specific number of rows to see the triangle being printed.
printTriangle(5);
When you run this code, you will see the following output:
*
**
***
****
*****
This is a right-angled triangle with 5 rows, each row containing an increasing number of asterisks.
If you want to print an inverted triangle, where the number of asterisks decreases with each row, you can modify the function as follows:
function printInvertedTriangle(rows) {
// outer loop to iterate through each row
for (let i = rows; i > 0; i--) {
// inner loop to print asterisks for each row
let asterisks = '';
for (let j = 1; j <= i; j++) {
asterisks += '*';
}
console.log(asterisks);
}
}
To print an inverted triangle with 5 rows, you can call the printInvertedTriangle
function as follows:
printInvertedTriangle(5);
Now, when you run this code, you will see the following output:
*****
****
***
**
*
This is an inverted triangle with 5 rows, where the number of asterisks decreases with each row.
You can modify and customize these functions according to your requirements to print different types of triangles using asterisks in JavaScript. Experiment with different input values for the rows
parameter to see how the triangle shape changes. Happy coding!