Experiment 7-2-6 Printing Yanghui's Triangle (20 points) This question requires that the first N lines of Yanghui's triangle be printed according to the specified format. Input format: The input gives N in one line (1≤N≤10). Output format: Output the first N rows of Yanghui triangles in equilateral triangle format. Each number occupies a fixed 4 bits. Input sample: 6 Sample output: 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 1 5 10 10 5 1 #include <stdio.h> #define N 11 //The requirement of 10 lines can be completed, and the two-dimensional array is stored according to the subscript 1. //Time: April 23, 2018 18:42:03 //Idea: first define a two-dimensional array a[][], and then initialize the array: first initialize all 1s of the boundary // Reinitialize non-boundary elements. After initialization, control the output format. // Note: The first 1 in the last line is directly output by %4d control, no additional spaces are required. intmain() { int i, j, k, n, a[N][N]; //Define a two-dimensional array a[11[11] with 11 rows and 11 columns scanf("%d", &n); for (i = 1; i <= n; i++) //initialize the boundary elements of the two-dimensional array elements { a[i][1] = a[i][i] = 1; //The numbers on both sides make it 1, because now the loop starts from 1, it is considered that a[i][1] is the first number } for (i = 3; i <= n; i++) //initialize non-boundary elements of two-dimensional array elements { for (j = 2; j <= i - 1; j++) { a[i][j] = a[i - 1][j - 1] + a[i - 1][j]; //Except the numbers on both sides are equal to the sum of the top two numbers } } for (i = 1; i <= n; i++) //Format control output, the last line is to directly output the first array element { for (k = 1; k <= n - i; k++) { printf("#"); //Print space placeholders before outputting array elements } for (j = 1; j <= i; j++) //output the elements in the initialized two-dimensional array { printf("%4d", a[i][j]); } printf("\n"); //When a line is output, wrap it } return 0; }
Experiment 7-2-6 Printing Yanghui's Triangle (20 points)
Guess you like
Origin http://43.154.161.224:23101/article/api/json?id=324774062&siteId=291194637
Ranking