Description: 1. The problem stems from "C language Classics, interesting, practical programming programming hundred examples of fine solutions", all the procedures for myself to write. Marked with a difference from the original program.
2. All programs in this series are compiled with Codeblocks and the operating system is Windows XP.
Problem: Display Yang Hui triangle on screen
1
1 1
1 2 1
1 3 3 1
1 4 6) 4 1
1 5 10 10 5 1
....................................
Analysis: I use the characteristics of graphics, design two arrays, the loop output, the code is as follows.
#include <stdio.h>#include<stdlib.h>intMainvoid){ intI=0, j=0; inta[ -]={0}, b[ -]={0}; a[0]=1; intRows=1; printf ("Please input rows:"); scanf ("%d", &rows);//control how many lines are output for(i=1; i<=rows; i++) { for(j=0; j<rows-i; J + +)//control the space before each line of the output{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 line through array b{A[j]= b[j-1] +B[j]; } for(j=0; j<rows; J + +)//output a new line of array a { 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 exactly the coefficient of the N-Power expansion of the (x+y). From the characteristics of Yang Hui triangle, we can summarize:
1) The nth line has a n+1 value (set the starting behavior 0 lines);
2) for the nth row of the J value: (n>=2);
When J=1 or j=n+1: the value is 1;
J! =1 and J! =n+1: The value is the J-1 value of the N-1 row and the value of the first J.
The above features are refined into mathematical formulas that can be expressed as:
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>intYanghui (intXinty);intMainvoid){ intI, J, n= -; printf ("n="); while(n> A) scanf ("%d", &n);//control Enter the correct values to ensure that the graphics on the screen are displayed correctly for(i=0; i<=n; i++)//control output N rows { for(j=0; j< --2*i; J + +) printf (" ");//control output Space before line I for(j=1; j<i+2; J + +) printf ("%4d", Yanghui (i, j));//outputs the J value of line Iprintf ("\ n"); } return 0;}intYanghui (intXinty) { intZ; if((y==1)|| (y==x+1)) return 1; Z=yanghui (x1, Y1) +yanghui (x1, y); returnZ;}
The output is as follows:
Figure 2
Fun C program 100.9 draw Yang Hui Triangle