Surviving the Technical Interview

Dr. Dobb's Journal Fall 1998

By Jay Sutaria

(a)
int iterative_factorial (int number) {
     int rval = 1;
     /* first check input values */
     if (number < 0) {
          /* we'll return -1 if there's an error */
          return (-1);
     }
     for (int i = number; i > 1; i--) {
          rval = rval * i;
     }
     return (rval);
}

(b)
int recursive_factorial (int number) {
     if (number < 0) {
          /* we'll return -1 if there's an error */
          return (-1);
     }
     else if ((number == 0) || (number == 1)) {
          return (1);
     }
     else {
          return recursive_factorial (number-1) * number;
     }
}

Example 1: Function that returns the factorial of a number: (a) iterative; (b) recursive.

Back to Article


Copyright © 1998, Dr. Dobb's Journal