Sunday, March 11, 2018

Addition of two Binary numbers using C

Addition of two Binary numbers using C 

The operation of adding two binary numbers is one of the fundamental tasks performed by a digital computer. The four basic addition operations are 0 + 0 = 0, 1 + 0 = 1, 0 + 1 = 1 and 1 + 1 = 10. In the first three operations, each binary addition gives sum as one bit , i.e. , either 0 or 1.But the fourth addition operation gives a sum that consists of two binary digits. In such result of the addition, lower significant bit is called as the sum bit, whereas the higher significant bit is called as the carry bit.


Binary Addition of Two Bits
0011
+ 0+ 1+ 0+ 1
011(carry) 1←0





C Program for addition of two binary Numbers:

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

int main()
{
    long int binary1, binary2;
    int i = 0, remainder = 0, sum[20];
    printf("Enter any first binary number :");
    scanf("%ld", &binary1);
    printf("Enter any second binary number :");
    scanf("%ld", &binary2);

    while(binary1!= 0 || binary2 != 0)
    {
        sum[i++] = (binary1 % 10 + binary2 % 10 + remainder) % 2;
        remainder = (binary1 % 10 + binary2 % 10 + remainder) / 2;
        binary1 = binary1 / 10;
        binary2 = binary2 / 10;
    }

    if(remainder != 0)
        sum[i++] = remainder;
    --i;
    printf("Sum of two binary numbers :");
    while(i >= 0)
        printf("%d", sum[i--]);

    return 0;
}


Sample Output:
 


No comments:

Post a Comment

Addition of two Binary numbers using C

Addition of two Binary numbers using C  The operation of adding two binary numbers is one of the fundamental tasks performed by a digita...