Add two big number using string in C

How to Add two big number 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:


1234...
1234...
______
2568...

We just add from last string and store the sum in an array. Then just print them from the last element of the array.
Have a look :
char str1 [ ] = "1234..." ;
char str2 [ ] = "1234..." ;

Then,  str1 [3] + str2 [3] = '4' + '4' = 104

Oops, What happened? It must be 8. OK, not to worry, here the sum is a ASCII value. So we must subtract 0 from 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 it's 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 sum 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 sum > 9, carry become 1 otherwise it remains 0.

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

Code for adding two big number

Happy Coding...

0/Post a Comment/Comments