Home » Java » Java print Yang Hui triangle

Java print Yang Hui triangle

declares an array of rows of row columns; row;

The first column and the diagonal value are 1, and the values of the other columns are the sum of the elements above and above the left upper; and

Assign the array and print.


public class YangHui
{
public, static, void, main (String[], args)
{
int row=10; // line number
int[][] p=new int[row][row];
// assignment
for (int i=0; i{
for (int j=0; j<=i; j++)
{
// the elements of the first column and the diagonal column are 1
if (j==0 j==i ||)
{
P[i][j]=1;
}else
{
// the value of other elements is the sum of the elements above and above the left upper
P[i][j]=p[i-1][j]+p[i-1][j-1];
}
}
}
// print output
for (int i=0; i{
// print space
for (int k=0; k<=2* (Row-I) -1; k++)
{
System.out.print ( "" ");
}
// print array
for (int j=0; j<=i; j++)
{
System.out.print (p[i][j]+ "" ");
}
System.out.println ();
}
}
}

Latest