This blog is under construction

Saturday, 12 May 2012

Recursive function in C

A function calls itself again and again until a particular condition is satisfied is called recursive function.

Recursive function example in C:
      int fact(int num) {
               if (num) {
                       return(num * fact(num - 1));
               }
               return (1);  
      }


Example C program for recursive function
 
  #include <stdio.h>
   /*
    * prints first 15 entries of given multiplication table
    * op1 X op2 = res
    * op1 - operand1
    * op2 - operand2
    * res = op1 X op2
    */
  void multiply(int op1, int op2, int res) {
        /* prints first 15 entries of op2 table */
        if (op1 > 15) {
                return;
        }
        res = op2 + res;
        printf("%03d X %03d = %03d\n", op1, op2, res);
        op1 = op1 + 1;
        return (multiply(op1, op2, res));  // recursive call
  }

  int main() {
        int input;
        printf("Enter your desired multiplication table:");
        scanf("%d", &input);  // input table
        multiply(1, input, 0); // prints "input" multiplication table
        return 0;
  }

  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter your desired multiplication table:10
  001 X 010 = 010
  002 X 010 = 020
  003 X 010 = 030
  004 X 010 = 040
  005 X 010 = 050
  006 X 010 = 060
  007 X 010 = 070
  008 X 010 = 080
  009 X 010 = 090
  010 X 010 = 100
  011 X 010 = 110
  012 X 010 = 120
  013 X 010 = 130
  014 X 010 = 140
  015 X 010 = 150



No comments:

Post a Comment