In this article, we will write Java program to print Floyd’s triangle and Pascal’s Triangle.
Floyd’s triangle
Floyd’s triangle is a right-angled triangular array of natural numbers.
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
package com.topjavatutorial; public class FloydTriangle { public static void main(String[] args) { int i, j, k = 1; for (i = 1; i <= 5; i++) { for (j = 1; j < i + 1; j++) { System.out.print(k++ + " "); } System.out.println(); } } }
Pascal’s triangle
Pascal’s triangle is a triangular array of the binomial coefficients.
It is named after Blaise Pascal.
The triangle may be constructed in the following manner: In row 0 (the topmost row), there is a unique nonzero entry 1. Each entry of each subsequent row is constructed by adding the number above and to the left with the number above and to the right, treating blank entries as 0.
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
package com.topjavatutorial; public class PascalTriangle { public static void main(String[] args) { int n = 5; for (int i = 0; i < n; i++) { int number = 1; System.out.printf("%" + (n - i) * 2 + "s", ""); for (int j = 0; j <= i; j++) { System.out.printf("%4d", number); number = number * (i - j) / (j + 1); } System.out.println(); } } }
© 2016 – 2017, https:. All rights reserved. On republishing this post, you must provide link to original post