The Program is Addition of Large Integers.. Although This program is working But I want to know where i went wrong or what should i need to do to make it better..
# include <stdio.h>
# include <stdlib.h>
# include <ctype.h>
# include <string.h>
typedef struct poly
{
int *coeff;
int degree;
}poly;
void init(poly *, char *);
void add (poly ,poly ,poly *);
int main(void)
{
char num1[80],num2[80],*sum;
int i;
poly p1,p2,p3;
printf("\n\n Program Large Integer Arithmatics :- ADDITION");
printf("\n\n Enter 1st Number:");
fscanf(stdin,"%s",num1);
printf("\n\n Enter 2nd Number:");
fscanf(stdin,"%s",num2);
init(&p1,num1);
init(&p2,num2);
add(p1,p2,&p3);
for(i = 0 ;i <= p3.degree ; i++)
sum[i] = p3.coeff[i] + 48;
sum[i] = '\0';
printf("\n\t Addition = %s",strrev(sum));
free(p1.coeff);
free(p2.coeff);
free(p3.coeff);
return 0;
}
void init(poly *p, char *num)
{
int i,len,j;
len = strlen(num);
p->coeff = (int *) malloc( len * sizeof(int));
//printf("\n %d",len);
for ( i = len - 1 ,j = 0 ; i >= 0 ; i-- , j++)
p->coeff[j] = num[i] - 48;
p->degree = j - 1;
}
void add(poly p1 , poly p2 , poly *p3)
{
int i , l , carry = 0 , s;
l = p1.degree > p2.degree ? p1.degree : p2.degree;
p3->coeff = (int *) malloc ((l+1) * sizeof(int));
for(i = 0 ; i <= l ;i++)
{
if(i > p1.degree)
s = p2.coeff[i] + carry;
else if (i > p2.degree)
s = p1.coeff[i] + carry;
else
s = p1.coeff[i] + p2.coeff[i] + carry;
carry = 0;
carry = s / 10;
p3->coeff[i] = s % 10;
}
if(carry)
{
p3->coeff[i]=carry;
p3->degree= i;
}
else
p3->degree = i-1;
}
Any help will be appriciated.
thanks
vinit mittal