Jump to content


Check out our Community Blogs

Register and join over 40,000 other developers!


Recent Status Updates

View All Updates

Photo
- - - - -

C/C++: Adding two big numbers

c++ c ascii value

  • Please log in to reply
8 replies to this topic

#1 mdebnath

mdebnath

    CC Newcomer

  • Member
  • PipPip
  • 17 posts
  • Programming Language:C, Java, C++
  • Learning:C, Java, C++

Posted 01 October 2012 - 01:53 AM

C/C++: Adding two big numbers

Introduction
Adding two numbers is trivial. In C/C++, the simple mathematical expression such as sum = a + b will add variable 'a' and 'b' an put the result in the variable 'sum'. What is you want to add two number beyond the capacity of any data types in C/C++. Here in this article I have tried to implement addition of two numbers beyond any theoretical limit. Of course, here they are limited by the array size or memory capacity, but can be extended by getting the input numbers from two files and writing the result in another file. Thus the other variation of the same program can be: using character array, using linked list, using file. Here the program uses character array of numbers.

How to find the capacity of primitive data types
If you ask, how to find the capacity of the primitive data types in C/C++? Answer is simple, try writing the following program to find out the integer limits. Same technique applies in finding the capacity of other primitive data types.

#include<stdio.h>
#include<limits.h>
int main(int argc, char **argv)
{
printf("%d", INT_MAX);
printf("%d", INT_MIN);
return 0;
}


The header file “limits.h” contains all the limits defined as constants such as CHAR_MAX, CHAR_MIN, LONG_MAX, LONG_MIN etc. You may check this by typing the following Linux command in the terminal.

$ man limits.h

Also readers should note that I have used GCC compiler, Fedora Linux platform, and Netbeans IDE for programming.

Thinking in code
Logic is pretty simple: we need two character arrays s1[255], s2[255] to get the input stream of numbers as string from standard input(keyboard). For the purpose of calculation we need to convert this input string into integer, so we declare three integer array: num1[255], num2[255] and sum[255] for storing the result. We then convert the character(number) from array s1 to num1 by subtracting ASCII value 48 or '0'. For example, integer 5 in ASCII is 53. To get the integer value we do a simple math: 53 – 48 = 5. Similarly, all the values 0 through 9 can be obtained in much the same way. To make sure the resultant sum and carry a single digit we apply the following logic. For example, 9+9=18, 18 % 10= 8, a single digit sum and 18 / 10 = 1, a single digit carry.


for (; i >= 0 && j >= 0; i--, j--, k++) {
sum[k] = (num1[i] + num2[j] + carry) % 10;
carry = (num1[i] + num2[j] + carry) / 10;
}
Now the number of elements in the arrays as num1 and num2 can have three situations:
  • Number of elements in num1 = number of elements in num2. For example, 99 + 11 = {1}10, last carry {1} needs to be included in the sum[k], so
    else {	
    if (carry > 0)	
    sum[k++] = carry;	
    }

  • Number of elements in num1 > number of elements in num2. For example, 1299 + 11 = {13}10.
    Last carry {13} needs to be included in the sum[k]. To be noted which in turn may have further carry. Following code implements the logic so that carry does not get truncated.
    if (l1 > l2) {	
    while (i >= 0) {	
    sum[k++] = (num1[i] + carry) % 10;	
    carry = (num1[i--] + carry) / 10;	
    }	
    }

  • Number of elements in num1 < number of elements in num2. For example, 99 + 1234 = {13}33.
    Last carry {13} needs to be included in the sum[k]. Here also to be noted which in turn may have further carry. Following code implements the logic so that carry does not get truncated.
    else if (l1 < l2) {	
    while (j >= 0) {	
    sum[k++] = (num2[j] + carry) % 10;	
    carry = (num2[j--] + carry) / 10;	
    }	
    }
And the remaining part of the program is simply printing the resultant array in reverse order

for (k--; k >= 0; k--)
printf("%d", sum[k]);

For the sake of simplicity:
  • Only positive numbers are taken into account
  • The claim of unlimited addition is limited by array size
  • No checking is applied to validate/invalidate non numeric elements. The program may behave erratically in such a case
Putting it all together

#include<stdio.h>
int main() {
int num1[255], num2[255], sum[255];
char s1[255], s2[255];
int l1, l2;

printf("Enter Number1:");
scanf("%s", &s1);
printf("Enter Number2:");
scanf("%s", &s2);

/* convert character to integer*/

for (l1 = 0; s1[l1] != '\0'; l1++)
num1[l1] = s1[l1] - '0';

for (l2 = 0; s2[l2] != '\0'; l2++)
num2[l2] = s2[l2] - '0';

int carry = 0;
int k = 0;
int i = l1 - 1;
int j = l2 - 1;
for (; i >= 0 && j >= 0; i--, j--, k++) {
sum[k] = (num1[i] + num2[j] + carry) % 10;
carry = (num1[i] + num2[j] + carry) / 10;
}
if (l1 > l2) {

while (i >= 0) {
sum[k++] = (num1[i] + carry) % 10;
carry = (num1[i--] + carry) / 10;
}

} else if (l1 < l2) {
while (j >= 0) {
sum[k++] = (num2[j] + carry) % 10;
carry = (num2[j--] + carry) / 10;
}
} else {
if (carry > 0)
sum[k++] = carry;
}


printf("Result:");
for (k--; k >= 0; k--)
printf("%d", sum[k]);

return 0;
}

Output
output.jpg

Attached File  bigadd.zip   50.07KB   702 downloads
  • 0

#2 lespauled

lespauled

    CC Leader

  • Expert Member
  • PipPipPipPipPipPipPip
  • 1360 posts
  • Programming Language:C, C++, C#, JavaScript, PL/SQL, Delphi/Object Pascal, Visual Basic .NET, Pascal, Transact-SQL, Bash

Posted 02 October 2012 - 08:13 AM

Just a note:

1299 + 11 is not 1300. Might want to fix that.
  • 1
My Blog: http://forum.codecal...699-blog-77241/
"Women and Music: I'm always amazed by other people's choices." - David Lee Roth

#3 mdebnath

mdebnath

    CC Newcomer

  • Member
  • PipPip
  • 17 posts
  • Programming Language:C, Java, C++
  • Learning:C, Java, C++

Posted 02 October 2012 - 08:44 PM

problem fixed
  • 0

#4 Litaya

Litaya

    CC Lurker

  • Just Joined
  • Pip
  • 2 posts
  • Programming Language:Java, C++
  • Learning:Java, PHP

Posted 19 April 2014 - 02:33 AM

There is a problem: 

                 

           99+1 = 100,

       

       But the result is  "00"  through your program.  ;)


Edited by Litaya, 19 April 2014 - 02:34 AM.

  • 0

#5 psam

psam

    CC Regular

  • New Member
  • PipPipPip
  • 35 posts

Posted 09 June 2014 - 09:24 AM

Your code is quite inefficient. You're using chars, which have 256 bits, to represent numbers upto 10 (which would require 4 bits). Not only that, but most processors can handle 64 bits on a single operation. I'd look into a large number library if I were you, like gmp.


  • 0

#6 joydeb

joydeb

    CC Lurker

  • Just Joined
  • Pip
  • 2 posts

Posted 24 August 2014 - 09:34 PM

@Litaya....just add this lines of code.....the problem will be fixed........

code:

if(sum[k-1]!=carry)

sum[k++]=carry;

 

just add this two lines in the main program in the following loops....

if(l1>l2)

{

}


  • 0

#7 joydeb

joydeb

    CC Lurker

  • Just Joined
  • Pip
  • 2 posts

Posted 24 August 2014 - 10:18 PM

by mistake the previous code is posted....

here it is:............

code:

if(sum[k-1]!=carry)

sum[k++]=carry;

 

just add this two lines in the main program in the following loops....

if(l1>l2)

{

    while(i>=0)

    {

       .......

    }

    code:

}

      and inside

 

else if(l1<l2)

{

    while(j>=0)

    {

      ........

     }

     code:

}


by mistake the previous code is posted....

here it is:............

code:

if(sum[k-1]!=carry)

sum[k++]=carry;

 

just add this two lines in the main program in the following loops....

if(l1>l2)

{

    while(i>=0)

    {

       .......

    }

    code:

}

      and inside

 

else if(l1<l2)

{

    while(j>=0)

    {

      ........

     }

     code:

}


  • 0

#8 Litaya

Litaya

    CC Lurker

  • Just Joined
  • Pip
  • 2 posts
  • Programming Language:Java, C++
  • Learning:Java, PHP

Posted 30 August 2014 - 11:55 PM

@joydeb you are right. :thumbup1:


  • 0

#9 SuminLee

SuminLee

    CC Lurker

  • Just Joined
  • Pip
  • 1 posts

Posted 07 May 2015 - 11:21 PM

How about inputing 101 , 99

real result is 200 , but above revised code shows result 0200



So Instead of above two lines code, I will insert below codes.

if (carry!=0){
   sum[k]=carry;
   k=k+1;

}


  • 0





Also tagged with one or more of these keywords: c++, c, ascii value