Open In App

JavaScript Program to Print Floyd’s Pattern Triangle Pyramid

Last Updated : 04 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Floyd’s Triangle is a right-angled triangular array of natural numbers, used primarily in computer science education. It is named after Robert Floyd. Each row of the triangle corresponds to the sequence of consecutive natural numbers.

In this article, we will explore different approaches to implementing JavaScript programs to print Floyd’s Pattern Triangle Pyramid.

Floyd’s Triangle Example:

Input: 
5
Output:
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15

Using Nested Loops

This approach employs nested loops where the outer loop controls the rows of the triangle, and the inner loop handles the numbers within each row. It’s a straightforward method commonly used to generate Floyd’s Triangle, with each row being built by incrementing the number sequentially.

Example: The algorithm iterates through each row, appending sequential numbers, and incrementally displays the triangle efficiently generates and prints Floyd’s Triangle based on the specified number of rows.

Javascript




function printFloydsTriangle(rows) {
    let number = 1;
    for (let i = 1; i <= rows; i++) {
        let row = "";
        for (let j = 1; j <= i; j++) {
            row += number + " ";
            number++;
        }
        console.log(row);
    }
}
 
const numberOfRows = 5;
printFloydsTriangle(numberOfRows);


Output

1 
2 3 
4 5 6 
7 8 9 10 
11 12 13 14 15 

Using Recursion

This approach leverages recursion to generate Floyd’s Triangle. The function recursively constructs each row of the triangle while incrementing the row number and the number to be printed. While recursion may not be the most efficient solution for this task, it demonstrates an alternative method that emphasizes the use of function calls and termination conditions.

Example: A succinct JavaScript function, `printFloydsTriangleRecursive`, recursively generates and prints Floyd’s Triangle. It constructs each row, appends the current number, prints the row, and makes a recursive call until the specified number of rows is reached.

Javascript




function printFloydsTriangleRecursive(
    rows,
    currentRow = 1,
    number = 1) {
    if (currentRow > rows) {
        return;
    }
 
    let row = "";
    for (let i = 1; i <= currentRow; i++) {
        row += number + " ";
        number++;
    }
    console.log(row);
 
    printFloydsTriangleRecursive
        (
            rows,
            currentRow + 1,
            number
        );
}
 
const numberOfRows = 5;
printFloydsTriangleRecursive(numberOfRows);


Output

1 
2 3 
4 5 6 
7 8 9 10 
11 12 13 14 15 


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads