Write a c program to add two very large numbers

Write a c program to add two very large or big numbers

int main(){
    int a[255],b[255],sum[255];
    int ac=0,bc=0,sc=0;
    int reminder = 0,i;
    char num1[255],num2[255],*pa,*pb;
    printf("Enter first number : ");
    scanf("%s",&num1); //taking first number from user in string format
    printf("\nEnter second number : ");
    scanf("%s",&num2); //taking second number from user in string format

    pa = num1; //pointer to first number
    pb = num2; //pointer to second number

    //storing  first string number in the integer array
    while(*pa){  //loop while run untill it get null character
        a[ac++] = *pa++ - 48;  //48 is ASCII value of character zero

    //storing  first string number in the integer array
         b[bc++] = *pb++ - 48;

    //additin of two numbers
         for(i = ac;i > 0;i--){
             sum[sc++]= ((a[i-1] + b[--bc]) + reminder)%10;
             reminder = ((a[i-1] + b[bc]) + reminder)/10;
             sum[sc++] = b[--bc] + reminder;
             reminder = 0;
         for(i = bc;i > 0;i--){
             sum[sc++]= ((b[i-1] + a[--ac]) + reminder)%10;
            reminder = ((b[i-1] + a[ac]) + reminder)/10;
         if(ac==0 && reminder==1)
             sum[sc++] = reminder;
            sum[sc++] = a[--ac] + reminder;
                reminder = 0;
    printf("Sum of both number is : ");
    return 0;


rai said...

wenever numbers r unequal n der is a carry d output is incorrect
eg : 9+9999

Anonymous said...

i think..
we can take the size of result array not same as the greatest number sized.. instead take it greatest number size +1.
here in this case we can take 256 size for result array..
then there will not be wrong out put in case of carry..

Vamsi said...

i dont think so. ac and bc were positioned nicely, and algorithm is working backwards.. and copying the excess..

117022089543768790625 said...

Yeah... this is kind of a nice code, but there's this minor mistake you're mentioning and the fact that it uses static allocation for those arrays, which is not quite smart. It's easy to modify it though, and use the argc/argv declaration of the main function to dynamically allocate the arrays. Then the only restriction to the length of the input would be your system's stack size ;)

kutta song said...

The 89th (Oscar) Academy Awards ceremony, presented by the Academy of Motion Picture Arts and Sciences (AMPAS), will honor the best films of 2016 and will take place at the Dolby Theatre in Hollywood, California on February 26, 2017.

Peach Bowl said...

The UFC 209 : Woodley vs Thompson 2 is an upcoming mixed martial arts event produced by the Ultimate Fighting Championship that will be held on March 4, 2017 at the T-Mobile Arena in Paradise, Nevada, part of the Las Vegas metropolitan area.