(eden)Pascal triangle
题目名称
Pascal triangle
题目描述
By using two-dimensional array, write C program to display a table that represents a Pascal triangle of any size. In Pascal triangle, the first and the second rows are set to 1. Each element of the triangle (from the third row downward) is the sum of the element directly above it and the element to the left of the element directly above it. See the example Pascal triangle(size=5) below:
1 | ||||
1 | 1 | |||
1 | 2 | 1 | ||
1 | 3 | 3 | 1 | |
1 | 4 | 6 | 4 | 1 |
我的代码
“triangle.h”&"main.c"
1 #include<stdio.h> 2 int a[100][100] = {0}; 3 void printPascalTr(int size) { 4 a[1][1] = 1; 5 int i, j; 6 if (size >= 1) printf("1\t\n"); 7 for (i = 2; i <= size; i++) { 8 for (j = 1; j <= i; j++) { 9 a[i][j] = a[i - 1][j] + a[i - 1][j - 1]; 10 printf("%d\t", a[i][j]); 11 } 12 printf("\n"); 13 } 14 }
1 #include <stdio.h> 2 #include "triangle.h" 3 void printPascalTr(int size); 4 5 int main() { 6 int size; 7 printf("Enter Pascal triangle size:"); 8 scanf("%d", &size); 9 printPascalTr(size); 10 getchar(); 11 return 0; 12 } 13
标程代码
1 #ifndef triangle_h 2 #define triangle_h 3 #include <stdio.h> 4 void printPascalTr(int size) { 5 int PascalTr[size][size]; 6 int row, col; 7 // assign zero to every array element 8 for (row = 0; row < size; row++) 9 for (col = 0; col < size; col++) 10 PascalTr[row][col] = 0; 11 // first and second rows are set to 1s 12 PascalTr[0][0] = 1; 13 PascalTr[1][0] = 1; 14 PascalTr[1][1] = 1; 15 for (row = 2; row < size; row++) { 16 PascalTr[row][0] = 1; 17 for (col = 1; col <= row; col++) { 18 PascalTr[row][col] = PascalTr[row - 1][col - 1] 19 + PascalTr[row - 1][col]; 20 } 21 } 22 // display the Pascal Triangle 23 for (row = 0; row < size; row++) { 24 for (col = 0; col <= row; col++) { 25 printf("%d\t", PascalTr[row][col]); 26 } 27 printf("\n"); 28 } 29 } 30 #endif /* triangle_h */ 31
问题
主要是格式问题,题目中也给的不太清楚,同时自己不知道制表符“\t”是什么意思,感觉标程略复杂了点。
需要学习的地方
①制表符还有空格这些什么的;
②这种只打一个定义文件里面的还有很多不清楚,为什么在main.c里面已经有include"stdio.h"在子程序里面"triangle.h"还要打一次呢?还有变量是否公用这些问题,要去学习。
③标称里面这些define"",ifndef,endif是什么意思呢,要去学习一下。