0

Take as input N, the size of array. Take N more inputs - digits between 0 and 9 - and store that in an array. Take as input M, the size of second array and take M more input digits and store that in second array. Write a function that returns the sum of the numbers represented by the two arrays. Print the value returned.

Input:

4

1 0 2 9

5

3 4 5 6 7

Output:

3, 5, 5, 9, 6, END

Below is the code I have written for it, but it's not giving any result rather it crashes.

using namespace std;
int main()
{
    int tsum,n,m,s,carry=0;
    cin>>n;
    int a[n],sum[]={0};
    for(int i=0; i<n; i++)
    {
        cin>>a[i];
    }
    cin>>m;
    int b[m];
    for(int i=0; i<m; i++)
    {
        cin>>b[i];
    }
    s=max(n,m);
    sum[s] = {0};
    while(n>0 and m>0)
    {
        tsum=a[n]+b[m]+carry;
        sum[s] = tsum%10;
        carry = tsum/10;
        n--;
        m--;
        s--;
    }
    if(n>m)
    {
        while(n>0)
        {
            tsum=a[n]+carry;
            sum[s] = tsum%10;
            carry = tsum/10;
            n--;
            s--;
        }
    }
    if(m>n)
    {
        while(m>0)
        {
            tsum=b[m]+carry;
            sum[s] = tsum%10;
            carry = tsum/10;
            m--;
            s--;
        }
    }
    

    for (int i=1; i<s; i++)
    {
        cout<<sum[i]<<", ";
    }
    cout<<"END";
    return 0;
}```
einpoklum
  • 118,144
  • 57
  • 340
  • 684
  • 3
    Arrays do not grow. `sum` is array of 1 element and it can store exactly this much. The only index that you can use is `sum[0]`. – Yksisarvinen Jan 25 '21 at 08:44
  • @DEEKSHA SHARMA You need not the array sum. According to the description the function must return a number. – Vlad from Moscow Jan 25 '21 at 08:56
  • The best way to start your C++ journey is to read a [good introductory book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) first. – Evg Jan 25 '21 at 08:59
  • 1
    In addition to the other problems `cin>>n; int a[n];` is not legal C++ since in C++ array sizes must be compile time constants (not variables). – john Jan 25 '21 at 09:01
  • `int a[n]` and `tsum=a[n]+...` does not match ( the `n--;` only cames afterwards), `n` is not a valid index for an array of `n` elements. – mch Jan 25 '21 at 09:13
  • `int a[n]` -> [Why aren't variable-length arrays part of the C++ standard?](https://stackoverflow.com/questions/1887097/why-arent-variable-length-arrays-part-of-the-c-standard) – 463035818_is_not_an_ai Jan 25 '21 at 09:21
  • kindly guide me through any approach to solve it – DEEKSHA SHARMA Jan 25 '21 at 17:12
  • Can you please explain how the input produces the output?...I can't seem to figure it out... – jackw11111 Jan 25 '21 at 22:26
  • we need to add the array element-wise starting from the right side, considering the carry that gets carried on as we proceed. – DEEKSHA SHARMA Jan 26 '21 at 10:31

0 Answers0