- Related Questions & Answers
- C++ Program to Perform Addition Operation Using Bitwise Operators
- Python program addition of two matrix
- Divide Two Integers in C++
- C program for Addition and Multiplication by 2 using Bitwise Operations.
- Addition of two numbers without propagating Carry?
- Sum of Two Integers in Python
- C Program to Add two Integers
- Addition of two number using ‘-‘ operator?
- Range Addition in C++
- C++ Program to Find GCD of Two Numbers Using Recursive Euclid Algorithm
- JavaScript recursive loop to sum all integers from nested array?
- Design a TM to compute addition of two unary numbers
- Bitwise ORs of Subarrays in C++
- Even-odd turn game with two integers in C++
- Median in a stream of integers (running integers) in C++

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

In this problem, we are given two numbers. Our task is to create a C program for the Bitwise recursive addition of two integers.

The logic to find the sum using the Bitwise operations is similar to what we used to do when we were in preschool. For finding the sum, we used to add each digit of the number and if a carry is there, we add it to the next digit.

We will do a similar thing, find the sum using the XOR operator and check for the carry using the AND operation. If there is a carry we will add it back to the number otherwise not.

This is the logic of a **Half-Adder **which you might have learned in digital Electronics. Refer here…

Now, The sum is calculated using a^b i.e. an XOR b and we need to check for an extra carry that needs to be propagated if the first bit of both is set or so. And we need to add an extra set bit to the number.

So, a bit algorithm will be

**Step 1** − Find XOR of a and b i.e. a^b and store it in the result variable.

**Step 2** − Check if {(a & b) << 1} == 0

**Step 2.1** − If it is equal to 0, then print the result, it is the final result.

**Step 2.2** − If it is not equal to 0, then go to step 1, with a = {(a & b) << 1} and b = result.

Program to illustrate the working of the algorithm −

#include <stdio.h> int addNumbers(int a, int b) { int carry = (a & b) << 1; int result = a^b; if (carry == 0) return result; else addNumbers(carry, result); } int main(){ int a = 54, b = 897; printf("The sum of %d and %d using bitwise adding is %d", a, b, addNumbers(a, b)); return 0; }

The sum of 54 and 897 using bitwise adding is 951’

Advertisements