#include
using namespace std;
int main() {
int n,m,x,k;
int i,j,carry=0,sum=0;
int a[1000],b[1000],c[1000];
cin>>n;
for(i=0;i<n;i++)
{
cin>>a[i];
}
cin>>m;
for(i=0;i<m;i++)
{
cin>>b[i];
}
i=n-1,j=m-1;
k=0;
while(i>=0 || j>=0)
{
if(i<0)
{
sum=carry+b[j];
}
else if(j<0)
{
sum=carry+a[i];
}
else{
sum=(carry+a[i]+b[j]);
}
c[k]=(sum%10);
carry=sum/10;
i–;
j–;
k++;
}
x=max(n,m);
for(i=x-1;i>=0;i–)
{cout<<c[i]<<", ";}
cout<<“END”;
return 0;
}
Code not passing all test cases
Hi @shivansh.sm1
In your code you have forgot to add a case when there is a carry present after adding the first digit of both the arrays. For example when input is :
4
9 0 2 9
5
9 4 5 6 7
Your code is printing output as 0, 3, 5, 9, 6, END but its correct output is 1, 0, 3, 5, 9, 6, END.
So all you need to do is that after the while loop just check if carry is 1 or not and if it is one then just update c[k] = 1;
Here is your corrected code have a look :