C Program to Find the Sum of two Binary Numbers:
This is a C program to Find the Sum of two Binary Numbers.
Problem Description
This program finds the sum of two binary numbers.
Problem Solution
Take two binary numbers as input.
Add each bits from the two binary numbers separately starting from LSB.
The operations may be as follows.
Program/Source Code
/*
* C Program to Find the Sum of two Binary Numbers
*/
#include
int main()
{
long binary1, binary2;
int i = 0, ....
Show More
This is a C program to Find the Sum of two Binary Numbers.
Problem Description
This program finds the sum of two binary numbers.
Problem Solution
Take two binary numbers as input.
Add each bits from the two binary numbers separately starting from LSB.
The operations may be as follows.
Program/Source Code
/*
* C Program to Find the Sum of two Binary Numbers
*/
#include
int main()
{
long binary1, binary2;
int i = 0, remainder = 0, sum[20];
printf("Enter the first binary number: ");
scanf("%ld", &binary1);
printf("Enter the 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;
}
Program Explanation
Obtain the remainders of both the binary numbers.
Obtain the quotients of both the binary numbers.
Firstly add the remainders of both binary numbers and further add the variable remainder.
Obtain the remainder of the result got at step 5 when divided by 2 and store it in the array sum[].
Obtain the quotient of the result got at step 5 when divided by 2 and override the variable remainder with this value.
Override the variables binary1 and binary2 with their quotient got at step 4.
Repeat the steps 3-8 with the new values of binary1 and binary2 until both becomes zero.
When it becomes zero check if any remainder exits. If it is, then copy it into the array sum.
Print the sum as output.
Output:
Enter the first binary number: 100000
Enter the second binary number: 101010
Sum of two binary numbers: 1001010
show less