1.

Write the code to add two numbers without using arithmetic operators.

Answer»

The sum of two bits can be found by executing an XOR (^) operation on the two bits. A carry bit can be obtained by performing AND (&) on the two bits.

The logic SHOWN below is a simple Half Adder that may be USED to add two single bits. This logic can be extended to integers. If there are no set bits at the same position(s) in a and b, bitwise XOR (^) of a and b yields the sum of a and b. Bitwise AND (&) is used to include COMMON set bits as well. All carry bits are obtained by bitwise AND of a and b. To acquire the needed result, we compute (a & b) << 1 and add it to a ^ b.

// C Program for adding two numbers// without the use of arithmetic operators#include<stdio.h>int Addition(int a, int b){ // Iterate until no carry while (b != 0) { // carry now stores common //set bits of a and b unsigned carry = a & b; a = a ^ b; // Carry to be shifted by one so that on adding // it to a, we get the required sum b = carry << 1; } return a;}


Discussion

No Comment Found