【C Language】-- Yanghui Triangle

Table of contents

1. What is the Yang Hui triangle?

2. Implementation method

1. Right triangle version

2. Isosceles triangle version


1. What is the Yang Hui triangle?

Yang Hui's triangle , also known as Jia Xian's triangle and Pascal's triangle, is a geometric arrangement of binomial coefficients in a triangle.

Shaped like:

It is not difficult to see that there are obvious rules.

That is: the two hypotenuses of the picture are the number 1 , and the rest of the numbers are equal to the sum of the two numbers on the shoulder of the layer where it is located (that is, the upper layer) .

2. Implementation method

1. Right triangle version

As shown in the picture:

Let's first realize the simple version of Yang Hui's triangle above. Since this law is layer by layer, each layer must be based on the previous layer when outputting. To do this, we can set up a two-dimensional array to store these numbers, with each layer as a row of the array. If you don’t understand, please look directly at the diagram below, which is more intuitive.

 The advantage of the above is that our code can be written concisely, regularly, and not cumbersomely. Except for the first and last fixed 1 of each row , the rest can  be input and output by a[i][j] = a[i - 1][j - 1] + a[i - 1][j].

#include<stdio.h>
#define M 9
int main() {

	int a[M][M] = { 0 };

	for (int i = 0; i < M; i++) {
		
		for (int j = 0; j<=i; j++) {
			if (j == 0 || j == i) {
				a[i][j] = 1;
				printf("%d ", a[i][j]);
			}
			else {
				a[i][j] = a[i - 1][j - 1] + a[i - 1][j];
				printf("%d ",a[i][j]);
			}
		}
		printf("\n");
	}
	return 0;
}

result:

2. Isosceles triangle version

The isosceles triangle version is the real Yanghui triangle, so we have to consider the output of the space characters in each line.

It is not difficult to see that the output of space characters in each line is also regular.

#define M 13  //意为打印M行杨辉三角
int main() {

	int a[M][M] = { 0 };
	int tmp = M;
	for (int i = 0; i < M; i++) {
		
		for (int j = 0; j < tmp - 1;j++) {	
			printf("   "); //三个空格,格式好看
		}
		tmp--;

		for (int j = 0; j<=i; j++) {
			if (j == 0 || j == i) {
				a[i][j] = 1;
				printf("%3d   ", a[i][j]); //%3d占三个字符,再加三个空格,格式好看
			}
			else {
				a[i][j] = a[i - 1][j - 1] + a[i - 1][j];
				printf("%3d   ",a[i][j]);   //%3d占三个字符,再加三个空格,格式好看
			}
		}
		printf("\n");
	}
	return 0;
}

 result:

Guess you like

Origin blog.csdn.net/m0_73381672/article/details/131278108