C language: simply print Young's triangle using a two-dimensional array

Yang Hui's triangle, also known as Pascal's triangle, is a mathematical regular figure. Its construction rules are as follows:

  1. The two endpoint numbers of each row are 1.
  2. Starting on the third row, each number is the sum of the two numbers above it.
  3. Each row of numbers is symmetrical.
#include<stdio.h>
int main()
{
	int arr[50][50];//定义一个二维数组存储杨辉三角
	int i, j, n;
	scanf("%d", &n);
	//第一个for循环产生行
	for (i = 0;i < n;i++)
	{
		//嵌套for循环产生列
		for (j = 0;j <= i;j++)
		{
			//杨辉三角特性:每一行首尾元素都是1
			if (i == j || j == 0)//j==0是因为每一列的元素都是1,这里可以画图方便理解
			{
				arr[i][j] = 1;
			}
			else //计算中间元素值,根据杨辉三角的特性
				arr[i][j] = arr[i - 1][j - 1] + arr[i - 1][j];//这里画图做个示例就可以明白
		}
	}
	//接下来输出杨氏三角
	for (i = 0;i < n;i++)
	{
		for (j = 0;j <= i;j++)
		{
			printf("%-5d", arr[i][j]);// 打印每个元素,并且使用 %-5d 保证输出格式对齐
		}
		printf("\n");//每打印一行完毕就换行
	}
	return 0;
}

Attached is a sketch. Students can draw it themselves and then write it out.

Guess you like

Origin blog.csdn.net/zsd2829568515/article/details/134431659