C Program to add Two (Very) Large Numbers

Last Updated on by ICT Byte

include

include

int charToInt (char stringNumber)
{
return stringNumber – ‘0’;
}

int main ()
{
char first_number[] = “55”;
char second_number[] = “166”;
char sum_string[500], str, sum_string_rev[500];
int _first_number, _second_number;
int sum, first_number_length, second_number_length, carry, count_up_to;
first_number_length = strlen (first_number);
second_number_length = strlen (second_number);

count_up_to = first_number_length>second_number_length? first_number_length: second_number_length;
carry = 0;
int j=0;
for(int i=count_up_to-1; i>=0;i–,j++){
_first_number = 0;
_second_number = 0;
if(j<first_number_length){
_first_number = charToInt(first_number[first_number_length-j-1]);
}

  if(j<second_number_length){
     _second_number = charToInt(second_number[second_number_length-j-1]); 
  }

  sum = _first_number + _second_number + carry;
  if(sum>=10){
        carry = sum /10;
      sum = sum %10; 
  }else{
      carry = 0;
  }
sum_string[j] = sum + '0';

}

if(carry){
sum_string[j] = carry + ‘0’;
}else{
count_up_to–;
}
puts(first_number);
puts(second_number);
int begin;
int count = count_up_to;
for (begin = 0; begin <= count; begin++) {
sum_string_rev[begin] = sum_string[count_up_to];
count_up_to–;
}
sum_string_rev[begin] = ‘\0’;
puts(sum_string_rev);
return 0;
}

More From Author

5 Commands to View the Content of a File in Linux

Sorting Very large numbers – Insertion Sort in Ruby