How do I add two 50 digit numbers in C?

Get your inputs into character buffer in_a and in_b, and make a character buffer for your sum:

#define NDIG 50
char in_a[NDIG+1], in_b[NDIG+1], sum[NDIG+1];
     /* ^ Stored in MSD-first ASCII */

Ensure that the numbers are right-justified, so that (e.g.) 25 is represented as "048 times25\0" and not just "25\0". Assuming an un-justified string is in str, you justify this with the following (using in_a as the example—you probably want to make a function instead):

const size_t len = strlen(str);
assert(len <= NDIG);
memcpy(in_a + NDIG - len, str, len+1);
if(len < NDIG)
    memset(in_a, '0', NDIG - len);

Now, do exactly what you do when you add on paper: Iterate over the digits from least-significant (@end of array) to most-significant (@start), keeping track of a 1-or-0 carry and adding that in as you move on.

int i;
unsigned char carry; /*or bool, or whatever*/
for(carry=0, i=NDIG-1; i >= 0; i--)
    /* Pull the digit values out: */
    const unsigned char a = in_a[i] - '0';
    const unsigned char b = in_b[i] - '0';

    /* Compute an intermediate sum, which may have a value from 0 to 18 */
    unsigned char c = carry + a + b;

    /* Set the carry to 1 iff the result is >=10, and subtract 10 to ensure
     * the result is only one decimal digit. */
    if(!!(carry = (c >= 10)))
        c -= 10;

    /* Store the result in the output array, adding '0' to re-ASCIIfy it. */
    sum[i] = c + '0';
/* Terminate the sum string. */
sum[NDIG] = '\0';

Now you have a 50-digit string you can print out directly. Of course, you’ll usually want to find the first nonzero digit and start printing there instead:

const char *sump;
for(sump = sum; sump < sum + NDIG-1 && *sump == '0'; sump++)
/r/learnprogramming Thread