C language realizes printing Yanghui triangle on the screen

★What is the Yanghui triangle?
The Yanghui triangle is a geometric arrangement of binomial coefficients in a triangle. ( surpriseOkay! We don't care about this, just understand the picture below)


[Algorithm idea]: Looking at the Yanghui triangle above, we can get some rules. The numbers on both sides are 1, and the numbers in the third row are the sum of the two numbers above. Finding the above rules, we can directly perform conditional assignment and output in the two-dimensional array to get the result.

【Reference Code】:
#include<stdio.h>
#include<windows.h>

#define line 10

intmain()
{
	int i = 0;
	int j = 0;
	int arr[line][line] = { 0 };
	for (i = 0; i < line; i++)
	{
		for (j = 0; j < line; j++)
		{
			if (j == 0)
			{
				arr[i][j] = 1;
			}
			//The first column is assigned the value 0
			if (i == j)
			{
				arr[i][j] = 1;
			}
			// assign the diagonal to 0
			if ((i > 1) && (j > 0))
			{
				arr[i][j] = arr[i - 1][j] + arr[i - 1][j - 1];
			}	
			//Starting from the third row and the second column, each element is the sum of the upper element and the upper left element
		}
	}
	for (i = 0; i < line; i++)
	{
		for (j = 0; j < 2*line-2*i; j++)
		{
			printf(" ");
		}
		// print spaces
		for (j = 0; j <= i; j++)
		{
			printf("%-4d", arr[i][j]);
		}
		//print the value of the lower triangle element
		printf("\n");
	}
	system("pause");
	return 0;
}

【operation result】:

Reference source code: day8_3


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325944445&siteId=291194637