This blog is under construction

Sunday 7 July 2013

C program to subtract two numbers without using arithmetic operator

How to subtract two numbers without arithmetic operator?
Consider, x and y be two integers whose values are 10 and 5 correspondingly.

Find 2's complement for y and add it with x gives you the difference between x and y.  Please check the below link to know about how to add two numbers without using addition operator.


Write a C program to subtract two numbers without using subtraction operator.


  #include <stdio.h>

  /* adds two numbers without using arithmetic 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 a, b, bComplement, result;
        /* get the input from the user */
        printf ("Enter your first input:");
        scanf("%d", &a);
        printf("Enter your second input:");
        scanf("%d", &b);

        /* finding two's complement for b */
        bComplement = addition(~b, 1);

        /*
         *  adding a & b's two's complement provides
         *  difference of two numbers
         */
        result = addition(a, bComplement);
        printf("Difference b/w %d and %d is %d\n", a, b, result);
        return 0;
  }



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



No comments:

Post a Comment