This blog is under construction

Saturday 20 July 2013

C program to divide two numbers using recursion

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


  #include <stdio.h>

  /* division of two number using recursion */
  void division(int *num1, int *num2, int temp, int sign, int count) {
        if (*num1 < temp) {
                printf("%d\n", (count * sign));
                return;
        }

        /* num1 is count times of num2 */
        *num1 = *num1 - temp;
        *num2 = *num2 - 1;
        count++;
        /* finding division output using recursion */
        division(num1, num2, temp, sign, count);
        return;
  }

  int main() {
        int num1, num2, temp, sign = 1, count = 0;

        /* 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);

        /* if any one of the input is negative, output is also -ve */
        if ((num1 < 0 && num2 > 0) ||
                (num1 > 0 && num2 < 0)) {
                sign = -1;
        } else if (num1 == 0) {
                /* if numerator is 0, the o/p is also 0 */
                printf("Division of %d and %d is 0\n", num1, num2);
                return 0;
        } else if (num2 == 0) {
                /* if denominator is 0, divide by zero error */
                printf("Divide by Zero!!\n");
                return 0;
        }

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

        /* finding the absolute values of both the inputs */
        num1 = abs(num1);
        num2 = abs(num2);
        temp = num2;

        /* find division of two numbers using recursion */
        division(&num1, &num2, temp, sign, count);

        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter your first input:100
  Enter your second input:0
  Divide by Zero!!

  jp@jp-VirtualBox:~/$ ./a.out
  Enter your first input:0 
  Enter your second input:10
  Division of 0 and 10 is 0

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

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

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


No comments:

Post a Comment