Saturday, October 19, 2013

Program for Adding two binary numbers

Program:
#include<stdio.h>   //TESTED
#include<conio.h>
int main()
{
clrscr();
    long int binary1,binary2;
    int i=0,remainder = 0,sum[20];
printf("\nEnter binary number 2: ");
scanf("%ld",&binary1);
    printf("\nEnter binary number 2: ");
    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("\nSum of two binary numbers: ");
    while(i>=0)
        printf("%d",sum[i--]);
    getch();
    return 0;
}

Output:
Enter binary number 1: 10
Enter binary number 2: 11
Sum of two binary numbers:101

No comments: