Adding two very large numbers using char arrays

Hello there,

I wrote a program trying to add two very large numbers using char arrays and int arrays.

but I have a problem, I tried adding the number "99999999999999999999999999999999999999999999999999999999999999" and "1"

the result was "0000000000000000000000000000000000000000"

The program works on any other number than 9s. I don't know why.

Can you guys help me please? Thank you.

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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
  #include <iostream>
#include <string>
#include <stdlib.h>

using namespace std;

class Addition
{
private:
	//255 because CHAR_MAX is 255, CHAR_MIN is 0.
	//Because we have CHAR_MAX 255, int will also be 255.
	int Number1[255], Number2[255], sum[255];
	char String1[255], String2[255];
	//Length1=length of N1, Length2=length of N2.
	int Length1, Length2;
public:
	Addition(){};
	void __ADDITION();
};

void Addition::__ADDITION()
{
	scanf("%s", &String1);
	scanf("%s", &String2);

	/* convert character to integer*/

	for (Length1 = 0; String1[Length1] != '\0'; Length1++)
	{
	    Number1[Length1] = String1[Length1] - '0';
	}

	for (Length2 = 0; String2[Length2] != '\0'; Length2++)
	{
	    Number2[Length2] = String2[Length2] - '0';
	}
	
	if(String1 <= 0)
	{
	    cout << "Invalid input" << endl;
	}

	int carry = 0;
	int k = 0;
	int i = Length1 - 1;
	int j = Length2 - 1;
	
	for (; i >= 0 && j >= 0; i--, j--, k++) 
	{
		sum[k] = (Number1[i] + Number2[j] + carry) % 10;
		carry = (Number1[i] + Number2[j] + carry) / 10;
	}
	
	if (Length1 > Length2)
	{
		while (i >= 0) {
			sum[k++] = (Number1[i] + carry) % 10;
			carry = (Number1[i--] + carry) / 10;
		}

	}
	
	else if (Length1 < Length2)
	{
		while (j >= 0) {
			sum[k++] = (Number2[j] + carry) % 10;
			carry = (Number2[j--] + carry) / 10;
		}
	}
	else
	{
		if (carry > 0)
			sum[k++] = carry;
	}


	cout << "SUM = ";
	for (k--; k >= 0; k--)
	{
	   cout << sum[k];
	}

}

int main()
{
	cout << endl;
	cout << "Hello, this program calculates two large numbers using ASCII and Arrays." << endl;
	cout << "We can convert Char or String into Int using ASCII and specifically by " << endl
		<< "subtracting '0' or 48.";
	cout << endl;
	cout << endl;

	Addition instance1;
	instance1.__ADDITION();

	system("PAUSE");
	return 0;
}
Topic archived. No new replies allowed.