Interesting C program 100.9 draw Yang Hui triangle, 100.9 Yang Hui
Note: 1. This problem comes from the classical, interesting, and practical programming languages of C language. All programs are compiled by myself. It is marked as different from the original program.
2. All programs in this series are compiled using codeblocks, and the operating system is Windows XP.
Problem: The Yang Hui triangle is displayed on the screen.
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
....................................
Analysis: Based on the characteristics of graphics, I designed two arrays and output them cyclically. The Code is as follows.
# Include <stdio. h> # include <stdlib. h> int main (void) {int I = 0, j = 0; int a [20] = {0}, B [20] = {0 }; a [0] = 1; int rows = 1; printf ("Please input rows:"); scanf ("% d", & rows ); // control the number of rows output (I = 1; I <= rows; I ++) {for (j = 0; j <rows-I; j ++) // control the output space before each row {printf ("") ;}for (j = 0; j <rows; j ++) // copy array a to array B {B [j] = a [j];} for (j = 1; j <= I-1; j ++) // assign a value to the next row through array B {a [j] = B [J-1] + B [j];} for (j = 0; j <rows; j ++) // output a new row of array { If (a [j]! = 0) printf ("% 4d", a [j]);} printf ("\ n");} return 0 ;}
The output is as follows:
Figure 1
The original book analysis is as follows:
The number in the Yang Hui triangle is the coefficient of the N power expansion of (x + y. Starting from the characteristics of the Yang Hui triangle, we can summarize the following:
1) Row N has N + 1 values (set the starting behavior to 0 );
2) for the J value of row N: (N> = 2 );
When J = 1 or J = N + 1: The value is 1;
J! = 1 and J! = N + 1: The sum of the N-1 and J values for the J-1 row.
Refining the above features into a mathematical formula can be expressed:
1 x = 1 or x = N + 1
C (x, y) = c (x-1, Y-1) + c (x-1, y)
# Include <stdio. h> # include <stdlib. h> int YangHui (int x, int y); int main (void) {int I, j, n = 13; printf ("N = "); while (n> 12) scanf ("% d", & n); // control the correct input value to ensure that the displayed image is correct for (I = 0; I <= n; I ++) // control the output of N rows {for (j = 0; j <24-2 * I; j ++) printf (""); // control the space before the output line I for (j = 1; j <I + 2; j ++) printf ("% 4d", YangHui (I, j )); // output the j value of row I, printf ("\ n");} return 0;} int YangHui (int x, int y) {int z; if (y = 1) | (y = x + 1) return 1; z = YangHui (x-1, Y-1) + YangHui (x-1, y ); return z ;}
The output is as follows:
Figure 2