We can write solution for this problem in two way i.e.
- Using recursive method
- Using loop i.e. non-recursive method.
Here is the C program to perform sum of two numbers with the help of bit-wise operator using recursive method.
/* Recursive method : Sum of two numbers using bitwise operators */
#include<stdio.h>
int sum ( int numFirst, int numSecond )
{
if ( numSecond == 0 )
return numFirst;
/* Recursive call of sum ( )*/
return sum ( numFirst ^ numSecond, ( numFirst & numSecond ) << 1 );
}
int main ()
{
int result = 0;
int numOne = 10;
int numTwo = 25;
result = sum ( numOne, numTwo );
printf ("The Sum of %d and %d is %d \n", numOne, numTwo, result);
return 0;
}
Here is the C program to perform sum of two numbers with the help of bit-wise operator using loop or non-recursive method.
/* Non-Recursive method : Sum of two numbers using bitwise operators */
#include<stdio.h>
int sum ( int numFirst, int numSecond )
{
while ( numSecond != 0 )
{
int carry = numFirst & numSecond;
numFirst = numFirst ^ numSecond;
numSecond = carry << 1;
}
return numFirst;
}
int main ()
{
int result = 0;
int numOne = 10;
int numTwo = 25;
result = sum ( numOne, numTwo );
printf ( "The Sum of %d and %d is %d \n", numOne, numTwo, result );
return 0;
}
To contribute :
” If you like Advance Computing and would like to contribute, you can mail your article to “computingadvance@gmail.com”. You will get credit as your name , email id, designation with article on this blog. “