To Write C Program for Sum of Two Binary Numbers

Aim:

To write C program for sum of two binary numbers.

Algorithm:

Step 1: Convert the input into binaries and store it in variable and array
Step 2: Add the variable binaries with array[i] , i++;
Step 3: Add every result by add () function
Step 4: Display the last result
Step 5: End

Program:

#include<stdio.h>
#include <stdlib.h>
int long add(int k,int h)
{
int sum[100];
int i=0,temp=0;
printf("\n");
while(k!=0||h!=0)
{
sum[i]=(k%10+h%10+temp)%2;
temp=(k%10+h%10+temp)/2;
k=k/10;
h=h/10;	
i++;
}
if(temp!=0)
{
sum[i]=temp;	
}
while(i>=0)
{
printf("%d",sum[i]);
i--;
}}
int main()
{
int x,sum=0,y,a[100],b[100],j=1;
int i=0,temp=0;
int sum1=0;
printf("\nEnter the Two Number To Be Converted:");
scanf("%d%d",&x,&y);
while(x>0)
{
a[i]=x%2;
x=x/2;
if(a[i]==0)
{
j=j*10;
}
else{
sum=sum+j;
j=j*10;	
}
i++;
}
j=1;
int s=0;
while(y>0)
{
b[s]=y%2;
y=y/2;
if(b[s]==0)
{
j=j*10;
}
else{
sum1=sum1+j;
j=j*10;	
}
s++;
}
printf("\nConverted Binary Number 1 is:");
printf("%d",sum);
printf("\nConverted Binary Number 2 is:");
printf("%d",sum1);
printf("\nSum Of Binary Number is:");
add(sum,sum1);
return 0;
}

Execution:

Input:
45 63

Output:
Enter the Two Number To Be Converted:
Converted Binary Number 1 is:1011010
Converted Binary Number 2 is:1000011
Sum Of Binary Number is:
10011101

Result:

Thus the Program for Binary addition was executed Successfully.

Leave a Comment