Add two very large number using linked list (December,2020)

/*this program will add two large number(any number of digits)*/

#include<stdio.h>

#include<conio.h>
typedef struct linked
{
     int val;
     struct linked *next;
}lnk;

lnk *create();

lnk *add(lnk *,lnk *);

void disp(lnk *);

int main()
{
                    lnk *h1,*h2,*h3;

printf("\n\nEnter the first large number : ");
h1=create();
printf("\n\nEnter the second large number : ");
h2=create();
h3=add(h1,h2);

printf("\n\nResultant number : ");
disp(h3);
return 0;
}

lnk *create()
{
int a,m;
lnk *temp,*h=NULL;
char ch;
while((ch=getch())!=13)
{
printf("%c",ch);
temp=(lnk*)malloc(sizeof(lnk));
temp->val=ch-'0';
temp->next=h;
h=temp;
}
return h;
}

lnk *add(lnk *h1,lnk *h2)
{
lnk *h3=NULL,*temp,*ptr;
int cr,t=0;
while(h1!=NULL && h2!=NULL)
{
t=h1->val+h2->val+t;
cr=t%10;
temp=(lnk *)malloc(sizeof(lnk));
temp->val=cr;
temp->next=h3;
h3=temp;
t=t/10;
h1=h1->next;
h2=h2->next;
}
if(h1!=NULL && h2==NULL)
{
while(h1!=NULL)
{
t=h1->val+t;
cr=t%10;
temp=(lnk *)malloc(sizeof(lnk));
temp->val=cr;
temp->next=h3;
h3=temp;
t=t/10;
h1=h1->next;
}
}
if(h2!=NULL && h1==NULL)
{
while(h2!=NULL)
{
t=h2->val+t;
cr=t%10;
temp=(lnk *)malloc(sizeof(lnk));
temp->val=cr;
temp->next=h3;
h3=temp;
t=t/10;
h2=h2->next;
}
}
return h3;
}

void disp(lnk *h)
{
if(h==NULL)
return;
else
{
printf("%d",h->val);
disp(h->next);
}
}

Add two very large number using linked list (December,2020)

Normally, We always try to add two integer numbers using simple arithmetic operation. Moreover, We can add two , three or multiple numbers having multiple number of digits. But depending upon our primitive data type i.e. int in C, we have some restriction about the number of digits. Firstly, That restriction varies for different compiler, but my code will help you to overcome that restriction. As a result, This code will help you to add two numbers with any number of digits.

Leave a Reply