add two integers
Page 1 of 1 • Share •
add two integers
write a program to add two integers without using any arithmetic operators? 
Admin- Admin
- Posts: 39
Join date: 2008-08-03

Re: add two integers
#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));
}
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));
}

shivang- Posts: 22
Join date: 2008-08-11
Age: 20
Location: Tondon 174
Re: add two integers
k fine write dis code without recursion ..........
Admin- Admin
- Posts: 39
Join date: 2008-08-03

Re: add two integers
#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){
temp<<= 1;
temp|= (num1^num2^result)&1;
result= ((num1|num2)&result|num1&num2)&1;
num1>>= 1;
num2>>= 1;
}
for (i= ~0, result= ~i; i; i>>= 1){
result<<= 1;
result|= temp&1;
temp>>= 1;
}
printf("Sum: %d",result);
return 0;
}
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){
temp<<= 1;
temp|= (num1^num2^result)&1;
result= ((num1|num2)&result|num1&num2)&1;
num1>>= 1;
num2>>= 1;
}
for (i= ~0, result= ~i; i; i>>= 1){
result<<= 1;
result|= temp&1;
temp>>= 1;
}
printf("Sum: %d",result);
return 0;
}

shivang- Posts: 22
Join date: 2008-08-11
Age: 20
Location: Tondon 174
Permissions of this forum:
You cannot reply to topics in this forum





