C program for addition of binary numbers







C code for sum of two binary numbers:  


#include
<stdio.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:

Enter any first binary number: 1100011
Enter any second binary number: 1101
Sum of two binary numbers: 1110000


Alogrithm:

Rule of binary addition:
0 + 0 = 0
1 + 0 = 1
0 + 1 = 1
1 + 1 = 1 and carry = 1

Q1. What is the sum of the binary numbers 1101 and 1110?
Answer: 1101 + 1110 = 11011





6. Write a c program to convert octal number to hexadecimal number.
8. Write a c program to convert hexadecimal number to octal number.
9. Write a c program to convert hexadecimal number to decimal number.
10. Write a c program to convert binary number to octal number.
Post a Comment