GeekInterview.com
   Home |  Tech FAQ  |   Interview Questions |  Placement Papers |  Tech Articles |  Learn |  Freelance Projects |  Online Testing |  Geeks Talk |  Job Postings |  Knowledge Base | Site Search |  Add/Ask Question

  GeekInterview.com  >  Interview Questions  >  Programming  >  C

 Print  |  
Question:  Sum of two numbers without using arithmetic operators

Answer: ex:
int a=10;
int b=10;
int sum=a+b;
without using "+" operator calculate sum


July 07, 2008 12:22:08 #3
 ceren6   Member Since: July 2008    Total Comments: 2 

RE: sum of two numbers without using arithmetic operators
 

#include <stdio.h>

int main ()

{

unsigned int t = 0xffffffff;

unsigned int z = 1;

int a = 10, b = 10, sum = 0, r = 0;


while (t) {

int t1, t2;


t1 = a & 0x00000001;

t2 = b & 0x00000001;


if ((t1 ^ t2 ^ r) == 1) {

if (t1 == 1 && t2 == 1 && r == 1)

r = 1;

else

r = 0;

sum = sum | z;

} else {

if (t1 == 0 && t2 == 0 && r == 0)

r = 0;

else

r = 1;

}


a >>= 1;

b >>= 1;

z <<= 1;

t >>= 1;

}


printf ("sum: %dn", sum);


return 0;

}

     

 

Back To Question