How to Add Two Numbers Without Using Plus Operator in C

#include <stdio.h>
#include <conio.h>

unsigned int f (unsigned int a , unsigned int b);


unsigned int f (unsigned int a , unsigned int b)

{
   return a ?   f ( (a&b) << 1, a ^b) : b;
}

int main()

{

int a = 9;

int b = 7;

int c = f(a,b);

printf("Sum = %d", c);
getch();
return 0;

}


---------------------
Output: Sum = 16
---------------------

Description:

For Example a = 5 and b=1 then
f(5,1) --> returns f(2,4) --> returns f(0,6) --> returns 6

1) 5&1 (0101 & 0001) = 1 bit shifted = 2:  5^1 (0101 ^ 0001) = 4
2) 2&4 (0010 & 0100) = 0 bit shifted = 0:  2^4 (0010 ^ 0100) = 6
3) a = 0 so return b of 6

For Example a = 4 and b=3 then
f(4,3) --> returns f(0,7) --> returns 7

1) 4&3 (0100 & 0011) = 0 bit shifted = 0:  4^3  (0100 ^ 0011) = 7
2) a = 0 so return b of 7
Share on Google Plus

About Unknown

"I am Kapil Thakar, an Embedded Engineer cum Blogger wants to learn new things. I love to share my knowledge solutions to the problems. Interested in Blogging, Creative-Writing, SEO, Website Creation, Video Making, Editing, Affiliation Programs, Online Making Money."
    Blogger Comment
    Facebook Comment

0 comments :

Post a Comment

Related Posts Plugin for WordPress, Blogger...