What Is Floyd’s Triangle & How Can You Build It?

Gerardmistretta
3 min readApr 25, 2021

--

This was an exciting week for me. My career search is officially underway, and I had my very first technical interview. Throughout the weeks leading up to this moment, I had been practicing algorithms for hours on Leetcode and Binarysearch. I logged into the online interview feeling confident. Then, I ran into Floyd’s Triangle.

When asked what it was, I felt it best to be honest and say I wasn’t entirely sure. After mustering up an educated guess that was actually pretty close, I was asked to replicate it. That was when I realized, you truly never know what questions you might get asked in these interviews.

Maybe it’s because this was my first real interview, or maybe it is because this was my most recent deer-in-headlights moment; but I wanted to take the time to learn what exactly they were asking for, and how to successfully build it.

By definition, Floyd’s Triangle is a triangular array of natural numbers. It was named after computer scientist Robert W. Floyd, who is most known for his cycle-finding algorithm and his work on parsing.

Robert W. Floyd
Robert W. Floyd

Essentially, Floyd’s Triangle fills in rows of a triangle using consecutive numbers. The first number, and row, is always 1. All successive rows start at the left. The next number always follows by successive naturals, listing one more number than the line above.

To begin, you’re going to need create a function. Inside of this function, set a variable equal to 1; as well as a specified number of rows. Then, you will need to create nested for loops. The first loop will be used to create our rows up until the specified amount, while the nested loop is used to create our columns.

function triangle() {   let count = 1let rows = 8for(let i = 1; i <= rows; i++) {for(let j = 1; j <= i; j++, count++)

Finally, you need a way to print out your results. By using document.write(), you can fill each row with the appropriate amount of numbers, and drop down to the next row at the appropriate time.

function triangle() {   let count = 1
let rows = 8
for(let i = 1; i <= rows; i++) {
for(let j = 1; j <= i; j++, count++)
document.write(count + " ");
document.write("<br/ > \n");
}
}

Our example of 8 rows will print out something like this:

1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31 32 33 34 35 36

And there you go!

--

--