Thursday 12 July 2012

Program to add Binary numbers in C




Sample Output -





Code - 



/* Program to add two binary numbers (No validation included) */

/* Program is a combination of 3 programs

1. Decimal to Binary
2. Binary to Deimal
3. Binary Numbers addition

*/

//___ Including header files ____

#include<stdio.h>

#include<conio.h>

#include<math.h>

int binary_decimal(int binary_number);

int decimal_binary(int decimal_number);

int main()
{
int bi_number_first = 0, bi_number_second = 0, de_number_first = 0, de_number_second = 0, sum = 0;

printf("\n\n\t\t  _____ Program to add two binary numbers_____");

printf("\n\n\t\t\t ___ No Validations included __");

printf("\n\n  Enter the first binary number  - ");

scanf("%d", &bi_number_first);

printf("\n\n  Enter the second binary number - ");

scanf("%d", &bi_number_second);

de_number_first = binary_decimal(bi_number_first);

de_number_second = binary_decimal(bi_number_second);

sum = de_number_first + de_number_second;

sum = decimal_binary(sum);

printf("\n\n\t\t  Sum of %d and %d is %d", bi_number_first, bi_number_second, sum);

getch();

return 0;
}

int binary_decimal(int binary_number)

//__ Function to convert binary number to decimal number __

{
int decimal_number = 0, remainder = 0, counter = 0;

while(binary_number != 0)
{
remainder = binary_number % 10; //___ Extracting the digits ____

binary_number = binary_number / 10; //__ Creating a new number ____

decimal_number = decimal_number + remainder * pow(2,counter);

          //___ Forming the decimal number __

counter++;
}

return decimal_number;

}

int decimal_binary(int decimal_number)

//__ Function to convert decimal number to binary number __

{
int remainder = 0, binary_number = 0, counter = 1;

while(decimal_number != 0)
{
remainder = decimal_number % 2;

decimal_number = decimal_number / 2;

binary_number = binary_number  + remainder * counter ;
 
                //__ Forming the binary number __

counter = counter * 10;
}

return binary_number;
}

No comments:

Post a Comment