/* pascal.c: print rows of Pascal's triangle to stdout. The algorithm is simply to generate successive rows iteratively using the defining property of pascal's triangle: C(n,k) = C(n-1,k-1) + C(n-1,k). The program is written for simplicity rather than efficiency. The only tricky thing is getting the display to look right. We provide an option -c to compute the number of display columns needed without doing the display itself. Author: Terry R. McConnell Compile: cc -o pascal pascal.c */ #include #include #ifndef FALSE #define FALSE 0 #endif #ifndef TRUE #define TRUE 1 #endif #define PROGRAM_NAME "pascal" #define VERSION "1.0" #define MAX_ROWS 30 #define USAGE "usage: pascal [ -h -v] [-c rows] rows\n" #define HELP "\n\npascal [-h -v] [-c n] n \n\ print the first n rows of pascal's triangle to stdout.\n\ -h: print this helpful information\n\ -v: print version number and exit\n\ -c: print the number of columns required for display only \n\n" static int triangle[MAX_ROWS + 1][MAX_ROWS]; /* num_digits: count how man digits the argument has and return that number */ int num_digits(int n) { int d = 1; while(n=n/10)d++; return d; } /* print_centered: print the first argument centered in a field of width given by the second argument, to the extent possible. (The width is always the second argument, but the number may not be quite centered, depending on parity.) Return 0 if successful and 1 if not. */ int print_centered(int n, int width) { int nw; int pad_space; int i; nw = num_digits(n); if(width < nw) return 1; /* no can do */ pad_space = (width - nw)/2; for(i=0;i= argc){ fprintf(stderr,USAGE); return 1; } cols_option = TRUE; i++; continue; } /* Unknown option if we got to here */ fprintf(stderr,USAGE); return 1; } /* Make sure there is one arg left */ if((i+1) != argc){ fprintf(stderr,USAGE); return 1; } nrows = atoi(argv[i]); /* Sanity checks */ if(nrows == 0){ if(cols_option)printf("0\n"); exit(0); /* nothing to do */ } if(nrows < 0){ fprintf(stderr,"%s: %d is an invalid number of rows\n", PROGRAM_NAME,nrows); exit(1); } if(nrows > MAX_ROWS){ fprintf(stderr,"%s: %d > %d rows maximum\n",PROGRAM_NAME,nrows, MAX_ROWS); exit(1); } /* build the triangle */ triangle[0][0] = 1; for(i=1;i