Make Selenium Easy

Frequently Asked Java Program 06: Print a Floyd Triangle of given number of rows

Hello Folks,

As part of Frequently Asked Java Programs In Interviews For Freshers And Experienced, in this post we will see a Java program to Print a Floyd Triangle 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

A software Tester who is paid to judge products developed by others. Currently getting paid in American Dollars. Writing technical posts and creating YouTube videos are my hobbies.

1 thought on “Frequently Asked Java Program 06: Print a Floyd Triangle of given number of rows

Leave a Reply

Please wait...

Subscribe to new posts to become automation expert

Want to be notified when my new post is published? Get my posts in your inbox.