This blog is under construction

Saturday 20 July 2013

C program to add two numbers using recursion

Write a C program to add two numbers using recursion.


  #include <stdio.h>

  /* finds the sum of n1 and n2 using recursion */
  void sum(int *n1, int *n2, int sign) {
        if (*n2 == 0) {
                printf("%d", *n1);
                return;
        }

        /*
         * incase *n2 is negative, we need 
         * to subtract 1 from *n1 
         */
        *n1 = *n1 + (1 * sign);
        *n2 = *n2 - (1 * sign);

        /* recursively calling sum to find the sum of 2 numbers */
        sum(n1, n2, sign);

        return;
  }

  int main() {
        int num1, num2, sign;

        /* get the first input from the user */
        printf("Enter your first input:");
        scanf("%d", &num1);

        /* get the second input from the user */
        printf("Enter your second input:");
        scanf("%d", &num2);

        printf("Sum of %d and %d is ", num1, num2);

        sign = num2 < 0 ? -1 : 1;
        /* find the sum of num1 and num2 */
        sum(&num1, &num2, sign);

        printf("\n");
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter your first input:-100
  Enter your second input:-300
  Sum of -100 and -300 is -400

  jp@jp-VirtualBox:~/$ ./a.out
  Enter your first input:200
  Enter your second input:-100
  Sum of 200 and -100 is 100

  jp@jp-VirtualBox:~/$ ./a.out
  Enter your first input:100
  Enter your second input:200
  Sum of 100 and 200 is 300


No comments:

Post a Comment