using array to add large numbers

Hello guys,

one of my assignment question is asking to add large integers with like 20+ digits ....c++ doesn't allow it so i have to enter the number as a string and then change it to reversed integer and save each element in an array and then add each element alone ...so i wrote the code but i am stuck at a point that if one array have many more element than the other it doesn't show the sum of the of the first digits correctly and show a weird number ...here is my code ...the output should be something like this for example (562314253698+4587965234=566902218932)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#include <iostream>
#include <cstring>
#include <string>

using namespace std;

void readnum(int N[],int &length);
void sumNum(int N1[], int length1, int N2[], int length2);
int main()
{
    int N1[20],N2[20],length2=0,length=0;

    readnum(N1,length);
    readnum(N2,length2);
  sumNum(N1, length,N2, length2);

 return 0;
}
void readnum(int N[],int &length)
{
    string num="";
    int i=0,N1[20];
   cout<<"Enter a positive integer of at most 20 digits :";
      getline(cin,num);
    length=num.length();
    int z=0;
    for (i=length-1;i>=0;i--)
    {
        N[z]=static_cast<int>(num[i])-(48);

       z++;
    }

  cout<<endl;

}
void sumNum(int N1[], int length1, int N2[], int length2)
{
     int sum[20],x,i;
if (length1>length2)
{
    length2=length1;
}

        for ( x=0;x<length1;x++)
        {
        sum[x]=N1[x]+N2[x];
        if (sum[x]>=10)
        {
            sum[x]=sum[x]-10;
            N1[x+1]++;
        }
        }
        for (i=length1;i>=0;i--)
        {
            cout<<sum[i]<<" ";
        }
}
Last edited on
Edit your post and repaste your code within code tags: http://www.cplusplus.com/forum/articles/16853/
And remove the extra blank lines.
You likely have integer overflow, in which case a sum of type int greater than the integer maximum will start becoming negative. Try long.

I did a find+replace of all "int" with "long", then corrected line 9 to say "int main". That produces the expected output, albeit with spaces.

You can refactor the program to just add these numbers normally as long (no pun intended) as they're contained in a type that supports their size.
Topic archived. No new replies allowed.