Search This Blog

Translate This Page

Tuesday, 26 February 2013

Subtracting two numbers without using '-' operator

Subtracting two numbers without using '-' operator


#include <stdio.h>

int add(int a,int b)
{
int x;
x=a^b;
while(a&b)
{
b=((a&b)<<1);
a=x;
x=a^b;
//b=(a^b);
}
return x;
}
int sub(int a, int b) // add a with b's 2's complement.
{
return (add(a, add(~b, 1)));
}
int main() {
int a, b, res;
a = 3, b = 1;
printf ("Enter two no\n");
scanf ("%d %d",&a,&b);
res = sub(a, b);
printf("%d\n", res);
printf ("After Sub. is  no  %d",res);
return 0;
} 


output: 
Enter two no
10
5
After Sub. no is 5

No comments:

Post a Comment

Latest Current Visitor

World Clock Time, for View Click on Country