Print Yang Hui's triangles (number of rows can be entered by keyboard)
Source: Internet
Author: User
/*
Requirements: Instance
Print Yang Hui's triangles (number of rows can be entered by keyboard)
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
Analysis: See the pattern of this image
A: The first and last columns of any row are 1.
B: Starting with the third line, each data is the previous column on its previous line and the sum of the lines on its line.
Except the last column
Steps:
A: Define a two-dimensional array. If the number of rows is n, the number of columns is also defined as N. This n data comes from the keyboard input.
B: Give this two-dimensional array the first and last columns of any row are 1.
C; Assign values to other elements according to the rules
Starting with the third line, each data is the previous column on its previous line and the sum of the lines on its line. Except the last column
D: Traversing this two-dimensional array
*/
Import Java.util.Scanner;
public class HelloWorld {
public static void Main (string[] args) {
Scanner sc = new Scanner (system.in);
System.out.println ("Please enter the number of lines in the Yang Hui's triangle:");
int n =sc.nextint ();
Define a two-dimensional array
int[][] arr = new int [n][n];
Assign a value of 1 to the first and last columns of any row of this two-dimensional array
for (int x=0; x<arr.length; x + +) {
Arr[x][0]=1; The 1th column of any row.
Arr[x][x]=1; The last column of any row.
}
Assign values to other elements according to the rules
Starting with the third row, each data is the sum of the previous column on its previous line and the column on its previous line.
for (int x=2; x<arr.length; x + +) {
This if the y<=x has a small problem, is the last column of the problem, so here to subtract 1
And y should start with 1 too, because the first column has a value too.
for (int y=1; y<=x-1; y++) {
Each data is the previous row on its previous line and the sum of the columns on its previous line
Arr[x][y] = Arr[x-1][y-1] + arr[x-1][y];;
}
}
Traversing this two-dimensional array
for (int x=0; x<arr.length; x + +) {
for (int y=0; y<x; y++) {
System.out.print (arr[x][y]+ "T");
}
System.out.println ();
}
}
}
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.