Write a c program to subtract two numbers without using subtraction operator






Write a c program or code to subtract two numbers without using subtraction operator


#include<stdio.h>

int main(){
   
    int a,b;
    int sum;

    printf("Enter any two integers: ");
    scanf("%d%d",&a,&b);

    sum = a + ~b + 1;

    printf("Difference of two integers: %d",sum);

    return 0;
}

Sample Output:

Enter any two integers: 5 4
Difference of two integers: 1





14 comments:

  1. write a c program to display all even factors of a given number using function in c

    ReplyDelete
  2. can u give me a program in c to calculate the series 1+4+25+........+n using double loops

    ReplyDelete
  3. how is it possible solution of above example question
    sum=a+~b+1

    ReplyDelete
  4. This comment has been removed by the author.

    ReplyDelete
  5. Replies
    1. ~ is complement operator.
      if a=8 then a=1000(in binary form)
      and when we take ~a it becomes=0111(interchange 0's and1's)
      now 0001=7
      in the above example we have to do (a-b)
      a-b= a+(-b)
      =a+(~b+1)=a+~b+1

      Delete
    2. but a & b are integers, how does it convert them to binary form, calculate 2's compliment and return result back in int form???

      Delete
    3. but a & b are integers, how does it convert them to binary form, calculate 2's compliment and return result back in int form???

      Delete
  6. #include

    int main(){

    int a,b,i;


    printf("Enter any two integers: ");
    scanf("%d%d",&a,&b);
    for( i=0;i<b;i++)
    {
    a--;
    }

    printf("Sum of two integers: %d",a);

    return 0;
    }

    ReplyDelete
  7. #include

    int main(){

    int a,b,i;


    printf("Enter any two integers: ");
    scanf("%d%d",&a,&b);
    for( i=0;i<b;i++)
    {
    a--;
    }

    printf("Sum of two integers: %d",a);

    return 0;
    }

    ReplyDelete
  8. Why did we write int on the line 1 (i.e.,into main())

    ReplyDelete
  9. Why did we write int on the line 1 (i.e.,into main())

    ReplyDelete
  10. will it work for a=10,b=5
    coz binary value of a=1010,b=101,~b=010
    so sum=1010+010+1
    =1101 which 13 in decimal

    ReplyDelete