Addition of two number using array of unequal size
I tried my level best to get it done. But I would like to have a better solution in all terms.
Given 2 huge numbers as seperate digits, store them in array and process them and calculate the sum of 2 numbers and store the result in an array and print the sum.
Input: Number of digits:12 9 2 8 1 3 5 6 7 3 1 1 6 Number of digits:9 7 8 4 6 2 1 9 9 7 Output : 9 2 8 9 2 0 2 9 5 1 1 3
Input:
Number of digits:12 9 2 8 1 3 5 6 7 3 1 1 6 Number of digits:9 7 8 4 6 2 1 9 9 7
Output:
9 2 8 9 2 0 2 9 5 1 1 3
#include<stdio.h>
#include<stdlib.h>
int main()
{
int num1[]={9,9,9,9,9,9,9,9,9};
int num2[]={1,1,1};
int num1_n=sizeof(num1)/sizeof(int);
int num2_n=sizeof(num2)/sizeof(int);
int z=num1_n+num2_n;
int carry=0;
int digi=0;
int i=0;
int j=0;
int *num3;
if(num1_n>num2_n)
{
num3=(int*)malloc(sizeof(int)*(num1_n+1));
for(i=0;i<num1_n+1;i++)
{
num3[i]=0;
}
for(i=num1_n-1,j=num2_n-1;i>=0 || j>=0 ;i--)
{
num3[i+1]=num3[i+1]+num1[i]+num2[j];
printf("i %d j %d num3[i] %d num1[i] %d num2[i] %d\n",i,j,num3[i],num1[i],num2[j]);
if(num3[i+1]>9)
{
carry=1;
num3[i+1]=num3[i+1]%10;
}
if(carry==1)
{
num3[i]=1;
carry=0;
}
if(j>=0)
{
j--;
}
}
}
for(i=0;i<num1_n+1;i++)
{
printf("%d ",num3[i]);
}
return 0;
}
#include<stdio.h>
#include<stdlib.h>
int main()
{
int num1[]={9,9,9,9,9,9,9,9,9};
int num2[]={1,1,1};
int num1_n=sizeof(num1)/sizeof(int);
int num2_n=sizeof(num2)/sizeof(int);
int z=num1_n+num2_n;
int carry=0;
int digi=0;
int i=0;
int j=0;
int *num3;
if(num1_n>num2_n)
{
num3=(int*)malloc(sizeof(int)*(num1_n+1));
for(i=0;i<num1_n+1;i++)
{
num3[i]=0;
}
for(i=num1_n-1,j=num2_n-1;i>=0 || j>=0 ;i--)
{
num3[i+1]=num3[i+1]+num1[i]+num2[j];
printf("i %d j %d num3[i] %d num1[i] %d num2[i] %d\n",i,j,num3[i],num1[i],num2[j]);
if(num3[i+1]>9)
{
carry=1;
num3[i+1]=num3[i+1]%10;
}
if(carry==1)
{
num3[i]=1;
carry=0;
}
if(j>=0)
{
j--;
}
}
}
for(i=0;i<num1_n+1;i++)
{
printf("%d ",num3[i]);
}
return 0;
}