//mn.c  -- find C(m,n) -- copyLeft by tsaiwn@csie.nctu.edu.tw
// try:  tcc -DTC mn.c
// 思考: 如何改用 one-dimentional array ?
#include <stdio.h>
#include <stdlib.h>
#if  defined(TCC) || defined(TC)
 #include <alloc.h>
#endif
#define MAX 100
unsigned long int x[MAX+1][MAX+1];   // unsigned long
     // 4*101*101 =~  405 K bytes
void pascalTriangle(int);
void getMN(int*, int*);    // note the parameters
int main( ) {
    static char buf[888];
    int m, n;  
    unsigned long ans;    // note that ans is unsigned Long int
    printf("Give me m, n and I Will give you C(m, n).\n");
    pascalTriangle(MAX);
    printf("Give me integers m, n=? "); 
    fgets(buf, sizeof(buf), stdin);    // read full input Line
    sscanf(buf, "%d %d", &m, &n );   // note address of m and n
    while( m>=0 && n >= 0 ) {
       if(m<= MAX && n <= MAX && m >= n) {
          ans = x[m][n];
          printf(" C( %d, %d) = %lu\n", m, n, ans);  // %lu for ulong
       } else {     /* ignore this input or print some message */  }
       getMN(&m, &n);    // note that the parameters are addresses
    }
#if  defined(TCC) || defined(TC)
    printf("Core Left = %lu bytes\n", coreleft( ) );  // unsigned long
#endif
    printf("Bye bye.\n");
    return 0;
}
void pascalTriangle(int n) {  // construct Pascal Triangle of order n
   int row, col;
   for(row=0; row <= n; ++row) {
       x[row][0] = x[row][row] = 1;
       for(col=1; col <= row-1; ++col) {
          x[row][col] = x[row-1][col] + x[row-1][col-1];
       }
       //for(col=0; col <= row; ++col) printf("%5lu ", x[row][col]);
       //printf("\n");
   }
}
void getMN(int*m, int*n) {    // note the parameters are pointers
    static char buf[333];  int kk;
    printf("m, n=? "); 
    fgets(buf, sizeof(buf), stdin);
    kk = sscanf(buf, "%d %d", m, n );   // note m and n are pointer
    if(kk!=2) kk = sscanf(buf, "%d, %d", m, n );   // try another format
#ifdef DEBUG
    printf("kk = %d in getMN().\n", kk);
#endif
}
