describe:
Print the Yanghui triangle
Enter description:
The first line contains an integer number n. (1≤n≤30)
Output description:
Contains n lines, which are the first n lines of Yanghui's triangle.
E.g:
Input: 6
output:
1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 1 5 10 10 5 1
Ideas:
After many students wrote 2 layers of for loops, there is no more. The main reason is that it is more difficult to print 1 in the outermost layer. After solving the outermost 1, the inner number can be obtained through the properties of the Yanghui triangle.
We still have to use two-dimensional arrays to solve the problem by finding rules.
We start at line 0. 1 in row 0 corresponds to i = 0, j = 0; 1 in row 1 corresponds to i = 1, j = 0; i = 1, j = 1; 1 in row 2 corresponds to i = 2, j = 0; i = 2, j = 2; In this way, we find that 1 is printed when i == j, and, no matter how i changes, 1 is also printed when j = 0, so
if((i == j) || j == 0)
{
arr[i][j] = 1;
printf("%d ", arr[i][j]);
}
After solving the 1 in the outer layer, the numbers inside are solved very well. For example, arr[2][1] (that is, the number 2) = arr[1][0] + arr[1][1], or find the law and find:
arr[i][j] = arr[i - 1][j - 1] + arr[i - 1][j];
Then the complete code is as follows:
#include<stdio.h>
int main(void)
{
int n = 0;
int i = 0, j = 0;
int arr[30][30] = { 0 };
scanf("%d", &n);
for(i = 0; i < n; i++)
{
for(j = 0; j <= i; j++)
{
if(j == 0 || j == i)
{
arr[i][j] = 1;
printf("%d", arr[i][j]);
}
else
{
arr[i][j] = arr[i - 1][j - 1] + arr[i - 1][j];
printf("%d", arr[i][j]);
}
}
printf("\n");
}
return 0;
}
Some students may taste the sweetness of one-dimensional arrays on certain topics, and want to use one-dimensional arrays to solve this problem. However, the courage is commendable (0-0)!