Write a C program to output Yang Hui's triangle

introduce:

        Yang Hui's triangle is a geometric arrangement of binomial coefficients in a triangle. In Europe, this table is called Pascal's triangle . Pascal (1623--1662) discovered this law in 1654, 393 years later than Yang Hui and 600 years later than Jia Xian . Yang Hui's triangle is one of the outstanding research results of ancient Chinese mathematics. It visualizes the binomial coefficients in graphics and intuitively reflects some inherent algebraic properties of composite numbers from the graphics. It is a combination of discrete numbers and shapes.

 Premise: The number of endpoints and endings of each line is 1

  1. Each number is equal to the sum of the two numbers above it.

  2. The numbers in each row are symmetrical from left to right, starting from 1 and gradually increasing.

  3. The numbers on the nth row have n items.

  4. There are a total of [(1+n)n]/2 numbers in the first n lines.

  5. The m numbers in the nth row can be expressed as  C(n-1, m-1) , that is, the number of combinations of m-1 elements taken from n-1 different elements.

  6. The m-th number in the n-th line is equal to the n-m+1-th number, which is one of the properties of combined numbers.

  7. Each number is equal to the sum of the left and right numbers in the previous row. This property can be used to write out the whole Yanghui triangle. That is, the i-th number in the nth row (n>1) is equal to the sum of the i-1th number and the i-th number in the n-1th row, which is also one of the properties of the combination number. That is,  C(n,i)=C(n-1,i)+C(n-1,i-1) .

Programming implementation:

        According to the law C(n,i)=C(n-1,i)+C(n-1,i-1) , we can realize Yang Hui's triangle through a two-dimensional array.

code show as below:

#include <stdio.h>

#define N 15

int main(){
	int s[N][N] = {0};
	s[0][0] = 1;//第一行只有一个值需要手动赋值
	int i = 0;
	int j = 0;
	int k = 0;
	int n = 0;
	while(n<=0 || n>15){
		printf("请输入需要打印的行数:");
		scanf("%d",&n);
	}
	for(i = 1; i < n; i++){
		s[i][0] = 1;//给每行的第一列赋值						
		for(j = 1; j <= i; j++){ 
			s[i][j] = s[i-1][j] + s[i-1][j-1];//其他列的值根据规律赋值
		}
	}

	printf("%d行杨辉三角如图:\n",n);
	for(i = 0; i < n; i++){
		for(k=1;k<=n-i;k++)//让每行输出的数字看起来中间对齐形成三角形
            printf("   "); //调整合适的占位间距
		for(j = 0; j <= i; j++){
			printf("%-6d", s[i][j]);//%-6d使输出的数据左对齐并有一定的间距
		}
		printf("\n");
	}
	
	return 0;
}

The output is as follows:

 Notice:

         As the number of lines increases, the numbers in the middle of each line will become longer and longer, and the image displayed on the terminal will not be able to maintain the triangle shape and display regularity due to the length and spacing of the numbers, so we need to reasonably control the number of printed lines.

Guess you like

Origin blog.csdn.net/Little_Star0/article/details/127588142