This blog is under construction

Saturday 20 July 2013

C program to subtract two numbers using recursion

Write a C program to find difference of two numbers using recursion.


  #include <stdio.h>

  /* finds difference between num1 & num2 using recursion */
  void subtract(int *num1, int *num2, int sign) {
        if (*num2 == 0) {
                printf("%d\n", *num1);
                return;
        }

        /* finding difference using recursion */
        *num1 = *num1 - (sign * 1);
        *num2 = *num2 - (sign * 1);
        subtract(num1, num2, sign);
        return;
  }

  int main() {
        int n1, n2, sign;

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

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

        printf("Difference b/w %d and %d is ", n1, n2);

        /* incase n2 is negative */
        sign = n2 < 0 ? -1 : 1;

        /* finds difference between n1 and n2 */
        subtract(&n1, &n2, sign);

        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter your first input:100
  Enter your second input:80
  Difference b/w 100 and 80 is 20

  jp@jp-VirtualBox:~/$ ./a.out
  Enter your first input:80
  Enter your second input:100
  Difference b/w 80 and 100 is -20

  jp@jp-VirtualBox:~/$ ./a.out
  Enter your first input:-10
  Enter your second input:20
  Difference b/w -10 and 20 is -30


No comments:

Post a Comment