Java Program 06: Print a Floyd Triange of given number of rows

Problem: Write a java program to print a Floyd’s triangle for a given number of rows.
Solution:

Floyd’s triangle is a right-angled triangular array of natural numbers, used in computer science education. It is named after Robert Floyd. It is defined by filling the rows of the triangle with consecutive numbers, starting with a 1 in the top left corner:

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

 

Logic to draw such pattern:

  • In JAVA, such patterns are known as pyramid. We can easily draw using matrix.
  • First, we think about row count which will be user input. If user enters 5, there will be 5 rows in triangle. For N, there will be N rows in triangle. So we need to have a for loop which will keep track of number of rows. It must start with 1 and iterate till N.
  • Now consider number of columns. For first row, there is only column. For second row, there are only two columns. For nth row, there should be only N columns. So we need to use another for loop, which will start from 1 and keep counter till it reaches number of row.
  • Since, we need to print natural numbers in a order, we will initialize a variable and increment it after printing once.

Java Program:

Output:
Enter the number of rows:
7
Floyd Triangle of rows: 7
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

I hope this programming section would be very useful for you all. If you have any doubt, please comment or write to me.

If you like my posts, please like, comment, share and subscribe.

#HappyCoding

Author: Amod Mahajan

My name is Amod Mahajan and I am an IT employee with 4+ years of experience in Software testing and staying in Bengaluru. My area of interest is Automation testing. I started from basics and went throw so many selenium tutorials. Thanks to Mukesh Otwani as his tutorials are easy and cover basics to advance. I have habit of exploring concepts by deep diving. I used to make notes. I thought of sharing my knowledge through posts and now I am here. #KeepLearning #ShareLearning