The Floyd's triangle (named after Robert Floyd) algorithm is a right-angled triangular array of natural numbers. It is defined by filling the rows of the triangle with consecutive numbers, starting with the number one in the top left corner.
In Floyd triangle there are n integers in the nth row and a total of (n(n+1))/2 integers in n rows. This is a simple pattern to print but helpful in learning how to create other patterns. Key to develop pattern is using nested loops appropriately. This program will prompt user for number of rows and based on the input, it would print the Floyd’s triangle having the same number of rows. /* Program: It Prints Floyd's triangle based on user inputs * Input: Number of rows * output: floyd's triangle*/ import java.util.Scanner; class FloydTriangleExample { public static void main(String args[]) { int rows, number = 1, counter, j; //To get the user's input Scanner input = new Scanner(System.in); System.out.println("Enter the number of rows for floyd's triangle:"); //Copying user input into an integer variable named rows rows = input.nextInt(); System.out.println("Floyd's triangle"); System.out.println("****************"); for ( counter = 1 ; counter <= rows ; counter++ ) { for ( j = 1 ; j <= counter ; j++ ) { System.out.print(number+" "); //Incrementing the number value number++; } //For new line System.out.println(); } } }
Output:
Enter the number of rows for floyd's triangle: 6 Floyd's triangle **************** 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
ANOTHER CODE FOR FLOYD TRIANGLE
ANOTHER CODE FOR FLOYD TRIANGLE
-
No comments:
Post a Comment