Labels

Monday, April 19, 2010

How to add two numbers without using the plus operator?

How to add two numbers without using the plus operator?
Actually,


SUM = A XOR B
CARRY = A AND B


On a wicked note, you can add two numbers wihtout using the + operator as follows


p1:
#include<>
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;

}



p2:
int add(int a, int b){
if (!a) return b;
else
return add((a & b) <<>
}

p3:
#include<>
using namespace std;
int main()
{
int a,b,sum;
scanf("%d",&a);
scanf("%d",&b);
sum=printf("%*d%*d",a,a,b,b);
printf("\n");
printf("%d\n",sum);
system("pause");
return 0;
}

p4:
logic behind

#include<>
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;

}


here 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..

I think this may clear all ur doubts regarding this..

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"..

2 comments:

  1. abe itna dimag nahi lagate thodi common sense use karo
    it is easiest answer=a-(-b)

    ReplyDelete
  2. actually we don`t want to use arithmetic operator
    on doing a-(-b)
    =a+(2,s complement of -b)
    so here also it use + operator

    ReplyDelete