Tuesday, May 19, 2009

Addition of Binary Numbers

//Program To Add Binary Numbers

#include


struct dnode *binary(int n);
void print(struct dnode *head);
void add(struct dnode *p, struct dnode *q);


struct dnode
{
int data;
struct dnode *next;
struct dnode *prev;
}*head;


void main()
{
struct dnode *head1, *head2, *head3;
int x, n;
clrscr();

printf("\nEnter no of bits in binary number:");
scanf("%d", &n);
printf("\n\nEnter 1st binary number:");
head1 = binary(n);
printf("\n 1st binary number:");
print(head1);
printf("\n\nEnter 2nd binary number:");
head2 = binary(n);
printf("\n2nd binary number:");
print(head2);
printf("\n\nAddition of binary numbers:");
add(head1, head2);

getch();
}

struct dnode *binary(int n)
{
struct dnode *p, *q;
int i, x;
head = NULL;

for(i=0; i {
scanf("%d", &x);
if(x==1 x==0)
{
q = (struct dnode *)malloc(sizeof(struct dnode));
q->data = x;
q->next = q->prev = NULL;
if(head == NULL)
p = head = q;
else
{
p->next = q;
q->prev = p;
p = q;
}
}
else
{
printf("\nEnter either 0 0r 1!!!!");
i--;
}
}
return(head);
}

void print(struct dnode *head)
{
if(head == NULL)
printf("\nError!!!!!!");
else
{
while(head!=NULL)
{
printf(" %d",head->data);
head = head->next;
}
}
}

void add(struct dnode *p, struct dnode *q)
{
struct dnode *r;
int sum, carry = 0;
r = (struct dnode *)malloc(sizeof(struct dnode));
r->next = r->prev = NULL;
r = head;

if(p!=NULL)
while(p->next!=NULL)
p=p->next;
if(q!=NULL)
while(q->next!=NULL)
q=q->next;
if(r!=NULL)
while(r->next!=NULL)
r=r->next;

while(p q)
{
sum = p->data + q->data + carry;

if(sum == 0)
{
r->data = 0;
carry = 0;
}
else if(sum == 1)
{
r->data = 1;
carry = 0;
}
else if(sum == 2)
{
r->data = 0;
carry = 1;
}
else if(sum == 3)
{
r->data = 1;
carry = 1;
}
p = p->prev;
q = q->prev;
r = r->prev;
}
r = head;
printf("\n %d",carry);
while(head!=NULL)
{
printf(" %d",head->data);
head = head->next;
}
}

No comments:

Post a Comment