code:
// CPP program to sum two numbers represented two
// arrays.
#include <bits/stdc++.h>
using namespace std;
// Return sum of two number represented by the arrays.
// Size of a[] is greater than b[]. It is made sure
// be the wrapper function
void calSumUtil(int a[], int b[], int n,int m )
{
// array to store sum.
int sum;
vector vect;
int i = n - 1, j = m - 1;
int carry = 0, s = 0;
// Until we reach beginning of array.
// we are comparing only for second array
// because we have already compare the size
// of array in wrapper function.
while (j >= 0) {
// find sum of corresponding element
// of both arrays.
s = a[i] + b[j] + carry;
sum = (s % 10);
vect.push_back(sum);
// Finding carry for next sum.
carry = s / 10;
cout<<sum<<" "<<carry<<"**"<<endl;
i--;
j--;
}
// If second array size is less the first
// array size.
while (i >= 0) {
// Add carry to first array elements.
s = a[i] + carry;
sum = (s % 10);
vect.push_back(sum);
carry = s / 10;
cout<<sum<<" "<<carry<<"**"<<endl;
i--;
}
//int ans = 0;
// If there is carry on adding 0 index elements.
// append 1 to total sum.
if (carry)
vect.push_back(carry);
// Converting array into number.
reverse(vect.begin(), vect.end());
for (vector<int> :: iterator it = vect.begin() ; it != vect.end(); it++ ) {
cout<<*it<<", ";
}
cout<<"END"<<endl;
}
// Wrapper Function
// Driven Program
int main()
{
int m, n;
cin>>m;
int a[m];
for(int i = 0; i < m; i++)
cin>>a[i];
cin>>n;
int b[n];
for(int j = 0; j < n; j++)
cin>>b[j];
if (n >= m)
calSumUtil(a, b, m,n );
else
calSumUtil(b, a, n,m);
return 0;
}
o/p:
6 1**
9 0**
5 0**
5 0**
8 2194**
2194, 8, 5, 5, 9, 6, END
My code is giving anomalous output , please correct me where I am wrong.