Thursday, December 22, 2011

Add TWO Numbers without using PLUS operator

Add two integers using bit operators.

Logic 1:
#include< stdio.h >
int main()
{
int a=30000,b=20,sum;
char *p;
p=(char *)a;
sum= (int)&p[b]; //adding a & b
printf("%d",sum);
return 0;

}



Strategy:

p = (char *)a; so p holds the value of a as the starting address.
and now &p[b] will return the address after "b" number of bytes from the starting location.
so that address is then type cast to an integer..
But this logic is not a good one because the pointer may point to a memory location out of its scope as it holds the value of a as its starting address..
and that's why compiler all the time shows it as a "bad pointer"..

Logic 2:
#include<stdio.h>

int add(int a, int b){
if (!a) return b;
else
return add((a & b) << 1, a ^ b);
}

int main()
{
int sum= add(-11,4); //adding a & b
printf("%d",sum);
getchar();
return 0;
}

No comments:

Post a Comment