This code doesn't include any overflow error checking mechanism. It is not much difficult to implement one however.
#include <stdio.h>
int main(){
unsigned num1,num2,result=0,i=0,temp=0;
printf("Enter the two numbers:\n");
scanf("%d",&num1);
scanf("%d",&num2);
for (i= ~0; i; i>>= 1){ //ensure
that the body of the loop is executed 8*sizeof(unsigned) times where 8
is the number of bits in a byte. The number of bits in a byte can be
more than 8 on some machines.
temp<<= 1;
temp|= (num1^num2^result)&1;
result= ((num1|num2)&result|num1&num2)&1;//to understand this line and the one above take a look at the full adder circuit above
//here temp is the equivalent of S1 in the full adder circuit above and result is the equivalent of C1
num1>>= 1;
num2>>= 1;
}
//the bit order in temp would be in the reverse order. the following code snippet reverses the order
for (i= ~0, result= ~i; i; i>>= 1){
result<<= 1;
result|= temp&1;
temp>>= 1;
}
printf("Sum: %d",result);
return 0;
}
Here is another elegant solution that uses recursion
#include <stdio.h>
int add(int a, int b){
if (!a) return b;
else
return add((a & b) << 1, a ^ b);
}
int main(){
printf("Enter the two numbers: \n");
int a,b;
scanf("%d",&a);
scanf("%d",&b);
printf("Sum is: %d",add(a,b));
}
274 views
Usually answered in minutes!
×