/*---------------------------------------------------------------------- File : recsum.c Contents: recursive computation of the sum of the first n natural numbers Author : Christian Borgelt History : 14.05.1998 file created ----------------------------------------------------------------------*/ #include #include /*---------------------------------------------------------------------- Functions ----------------------------------------------------------------------*/ int sum (int n) { /* --- recursive summation function */ if (n <= 1) return 1; /* sum_{i=1}^1 = 1 */ return n + sum(n-1); /* sum_{i=1}^n = n +sum_{i=1}^{n-1} */ } /* sum() */ /*--------------------------------------------------------------------*/ int main (int argc, char *argv[]) { /* --- main function */ int n; /* upper bound of sum */ if (argc != 2) { /* if wrong number of arguments given */ printf("usage: %s n\n", argv[0]); printf("compute the sum of the first n natural numbers\n"); return 0; /* print a usage message */ } /* and abort the function */ n = atoi(argv[1]); /* get upper bound of sum */ if (n <= 0) { /* and check it */ printf("%s: n must be > 0\n", argv[0]); return -1; } printf("sum_{i=1}^{%i} i = %i\n", n, sum(n)); return 0; /* compute sum and return 'ok' */ } /* main() */