This blog is under construction

Sunday 7 July 2013

C program to divide two numbers without using division operator

How to divide two numbers without using division operator?
Consider x and y be two integers whose values are 10 and 2 correspondingly.  Find the number of y's in x.  This can be found by subtracting y from x continuously until the value of x becomes lesser value than y.
Example:
x = 10 - 2
x = 8 - 2
x = 6 - 2
x = 4 - 2
x = 2 - 2 = 0

Number of y's in x is 5 (10 has 5 twos)

To get better understanding, please check the below link to know about how to add/subtract two numbers without using arithmetic operator.


Write a C program to divide two numbers without using arithmetic operators.


  #include <stdio.h>

  /* addition of two numbers without using addition operator */
  int addition(int a, int b) {
        int carry;
        while (b != 0) {
                /* calculating the carry and do a left shift*/
                carry = (a & b) << 1;
                /* calculating the sum */
                a = a ^ b;
                b = carry;
        }
        return a;
  }

  int main () {
        int num1, num2, twosComplement, temp, res, count = 0, i;
        /* get the input from the user */
        printf ("Enter your first input:");
        scanf("%d", &num1);
        printf("Enter your second input:");
        scanf("%d", &num2);

        if (num1 < num2) {
                printf("Division of %d by %d is %d\n", num1, num2, 0);
                return 0;
        }

        res = num1;
        twosComplement = addition(~num2, 1);
        /*
         * Add num1 with 2's complement of num2 continuosly
         * until num1 becomes lesser value than num2.
         * Division of two numbers without using arithmetic
         * operator.
         */
        for (i = 0; res > 0; i++) {
                res = addition(res, twosComplement);
                if (res <= 0) {
                        if (res == 0)
                                count = addition(count, 1);
                        break;
                } else {
                        count = addition(count, 1);
                }
        }

        /* count is the quotient value */
        printf("Division of %d by %d is %d\n", num1, num2, count);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter your first input:100
  Enter your second input:2
  Division of 100 by 2 is 50



1 comment: