Sunday, August 16, 2009

Floyd Triangle Program in Java

Welcome back again, today at Java Code Online, I would be discussing the Java code for Floyd's Triangle.

The Floyd's triangle starts from 1, it is a right angled triangle, consisting of consecutive numbers. If suppose four rows of the Floyd's Triangle need to be generated, then the output will be, the first row contains 1, the second row contains 2 3, the third row contains 4 5 6, and the last row contains 7 8 9 10. I hope that will clear your concept about the Floyd's Triangle. One more intresting fact about this triangle is that all the last numbers of each row are Triangular numbers.

The Java Code provided, asks the user to enter the number of rows till which the Floyd's Triangle is desired, and then generates it. The Java Program is given below:-

package developer;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class FloydTriangle {

static int counter = 0;
/**
* @param args
* @throws IOException
* @throws NumberFormatException
*/
public static void main(String[] args) throws NumberFormatException, IOException {
System.out.println("Enter the number of rows for Floyd Triangle:");
InputStreamReader ir = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(ir);


int num = Integer.parseInt(br.readLine());

for(int i = 1; i <= num; i++)
{
for(int j = 1; j <= i; j++)
{
counter = counter + 1;
System.out.print(counter);
System.out.print(" ");
}
System.out.println("");
}

}
}

I hope that this post was helpful to you all. Kindly leave your comments in case you liked the above code. For more info on Java, keep buzzing Java Code Online.

2 comments:

  1. The code is great. You helped me a lot regarding the java codes and concepts. I have already added you in my bookmarks. Thanks again for the code.

    ReplyDelete
  2. Recently, I have an assignment for Floyd Triangle in Java. My professor kept me thinking about the structure of the Floyd's triangle. Your Java Code was a great help. I also need some help regarding file handling Java codes, I suppose you can help me on that too...

    ReplyDelete

Note: Only a member of this blog may post a comment.