In this post, I am will show you to write a simple JavaScript function to print Floyd’s Triangle pattern. If you don’t know what is Floyd’s Triangle, here is an explanation.
What is Floyd’s Triangle?
Floyd’s triangle is a right-angled triangular array of natural numbers, used in computer science education. It is named after Robert Floyd, who invented it in 1987. The first row contains a single number 1, and each subsequent row contains one more number than the previous row. The numbers are arranged in the triangle such that they form a sequence of consecutive natural numbers.
Here’s an example of Floyd’s triangle with 5 rows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Now you know what is Floyd’s triangle, let us write the JavaScript program to print the same:
function floydsTriangle(n) {
let num = 1;
for (let i = 1; i <= n; i++) {
for (let j = 1; j <= i; j++) {
process.stdout.write(num + " ");
num++;
}
console.log();
}
}
floydsTriangle(5);
/*
Output:
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
*/