programming-examples/c/Basic/C Program to Input 2 Binary Strings and Print their Binary Sum.c

118 lines
2.7 KiB
C
Raw Normal View History

2019-11-18 14:44:36 +01:00
/*
* C Program to Input 2 Binary Strings and Print their Binary
* Sum
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int bin_verify(char []);
void sum(char [], char [], char []);
int main()
{
char bin1[33], bin2[33], result[33];
int len1, len2, check;
printf("Enter binary number 1: ");
scanf("%s", bin1);
printf("Enter binary number 2: ");
scanf("%s", bin2);
check = bin_verify(bin1);
if (check)
{
printf("Invalid binary number %s.
", bin1);
exit(0);
}
check = bin_verify(bin2);
if (check)
{
printf("Invalid binary number %s.
", bin2);
exit(0);
}
sum(bin1, bin2, result);
printf("%s + %s = %s
", bin1, bin2, result);
return 0;
}
int bin_verify(char str[])
{
int i;
for (i = 0; i < strlen(str); i++)
{
if ((str[i] - '0' != 1 ) && (str[i] - '0' != 0))
{
return 1;
}
}
return 0;
}
void sum(char bin1[], char bin2[], char result[])
{
int i = strlen(bin1) - 1;
int j = strlen(bin2) - 1;
int carry = 0, temp, num1, num2;
while (i > -1 && j > -1)
{
num1 = bin1[i] - '0';
num2 = bin2[j] - '0';
temp = num1 + num2 + carry;
if (temp / 2 == 1)
{
carry = 1;
temp %= 2;
}
if (i > j)
{
result[i + 1] = temp + '0';
result[strlen(bin1) + 1] = '';
}
else
{
result[j +1] = temp + '0';
result[strlen(bin2) + 1] = '';
}
i--;
j--;
}
while (i > -1)
{
temp = bin1[i] + carry - '0';
if (temp / 2 == 1)
{
carry = 1;
temp %= 2;
}
result[i + 1] = temp + '0';
i--;
}
while (j > -1)
{
temp = bin2[j] + carry - '0';
if (temp / 2 == 1)
{
carry = 1;
temp %= 2;
}
result[j + 1] = temp + '0';
j--;
}
if (carry)
{
result[0] = '1';
}
else
{
result[0] = '0';
}
}
Enter binary number 1: 0110
Enter binary number 2: 1011
0110 + 1011 = 10001