add two integers

Go down

add two integers

Post  Admin on Tue Aug 19, 2008 8:30 am

write a program to add two integers without using any arithmetic operators? Question

Admin
Admin

Posts : 39
Join date : 2008-08-03

View user profile http://computerclub09mnnit.forumotion.net

Back to top Go down

Re: add two integers

Post  shivang on Tue Aug 19, 2008 8:50 am

#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));
}
avatar
shivang

Posts : 22
Join date : 2008-08-11
Age : 29
Location : Tondon 174

View user profile

Back to top Go down

Re: add two integers

Post  Admin on Tue Aug 19, 2008 11:27 am

k fine write dis code without recursion ..........

Admin
Admin

Posts : 39
Join date : 2008-08-03

View user profile http://computerclub09mnnit.forumotion.net

Back to top Go down

Re: add two integers

Post  shivang on Tue Aug 19, 2008 12:24 pm

#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;
}
avatar
shivang

Posts : 22
Join date : 2008-08-11
Age : 29
Location : Tondon 174

View user profile

Back to top Go down

Re: add two integers

Post  Sponsored content


Sponsored content


Back to top Go down

Back to top


 
Permissions in this forum:
You cannot reply to topics in this forum