## How to Add two big numbers using string

It's easy to add two numbers in any programming language. For example, if int a = 2; int b = 3, then we just add a + b. Now, if we try to add two numbers, each having 100 digits like 10000000000000000000000000000000000...., what should we do?

There is no data type to hold 100 digits in a variable. So, what can we do? The process is to take input as a *string*. Then we can add those numbers.

For example:

We add from the last string and store the sum in an *array*. Then just print them from the last element of the array.

Oops, what happened? It must be 8. OK, not to worry, here the sum is an ASCII value. So, we must subtract 0 from the string.

So, (str1 [3] - '0' ) + (str2 [3] - '0') = 4 + 4 = 8;#### What happened here?

It's simple, in our string, str1 [3] = 4, which is a character, and its ASCII value is 52. If we subtract character 0 containing ASCII code 48. Then we get 52 - 48 = 4.

After doing this, we will store all the sums in an int-type array. Then we just print them from the last position of the array.

Now we got another problem. What happens when we add 129 + 124?

the last digit 9+4 = 13. In this case, we can use a carry and add the carrying value to the next addition. At first, carry is set to 0, and if the sum > 9, carry becomes 1; otherwise, it remains 0.

[Note: try to solve yourself, following the algorithm above. If failed, then see the code]

## Post a Comment