*C program for Binary Addition and Subtraction*

Write a C program to calculate Binary Addition and Binary Subtraction

Binary addition and binary subtractionis similar to regular (daily life) addition and binary subtraction, but hereaddition or subtractionperforms only two digits those are0 and 1, these are binary digits hence such kind of addition or subtraction is calledbinary addition and binary subtraction.

**Binary addition**

**Binary addition**

Binary Addition works in the same way, except that only 0’s and 1’s can be used, instead of the whole spectrum of 0-9. This actually makes binary addition much simpler than decimal addition, as we only need to remember the following:

**In binary addition**

0+0 = 0

0+1 = 1

1+0 = 1

1+1 = 0 (1 carries out)

**Example of Binary Addition:**

Take two numbers, suppose numbers are

10 and 20their binaries are1010 and 10100.

**Now add 10 and 20**

10 = 0 1 0 1 0

20 = 1 0 1 0 0

= 1 1 1 1 0

= 30

**Binary Subtraction**

**Binary Subtraction**

**Subtraction and Borrow**, these two words will be used very frequently for the binary subtraction. There are four rules of binary subtraction.

**In binary subtraction**

0-0 = 0

1-0 = 1

0-1 = 1 (1 borrows out)

1-1 = 0

**Example of Binary Subtraction:**

Take two numbers, suppose numbers are

20 and 10their binaries10100 and 1010.

**Now sub 10 from 20**

20 = 1 0 1 0 0

10 = 0 1 0 1 0

= 0 1 0 1 0

= 10

**SOURCE CODE : :**

**SOURCE CODE : :**

#include <stdio.h> //--------function for Binary Addition-------- int binAddition(int a,int b) { int c; //carry while (b != 0) { //find carry and shift it left c = (a & b) << 1; //find the sum a=a^b; b=c; } return a; } //-------Function for Binary Subtraction-------- int binSubtracton(int a, int b) { int carry; //get 2's compliment of b and add in a b = binAddition(~b, 1); while (b != 0) { //find carry and shift it left carry = (a & b) << 1; //find the sum a = a ^ b; b = carry; } return a; } int main() { int number1,number2, binAdd, binSub; printf("Input first integer value: "); scanf("%d",&number1); printf("Input second integer value: "); scanf("%d",&number2); binAdd=binAddition(number1,number2); binSub=binSubtracton(number1,number2); printf("Binary Addition: %d\n",binAdd); printf("Binary Subtraction: %d\n",binSub); return 0; }

**Also read : :****Write a C program to check date is valid or not**

**Output : :**

**Output : :**

Input first integer value: 12 Input second integer value: 5 Binary Addition: 17 Binary Subtraction: 7