Monday, April 5, 2010

Addition of Two 100 digit Number Program

#include < stdio.h >
#include < conio.h >
#include < string.h >
int main()
{
    char first[100],second[100];


    // here i use 100 digit if u use more than 100 then change the size

    int flength,slength,remain=0,fdata,sdata,i,ans,r1,s;
    clrscr();
    // Gather input from user first and second number
    printf("\n Enter the first number : ");
    scanf("%s",first);
    // Handle the input as a string then only you can store lot of digits
    printf("\n Enter the second number : ");
    scanf("%s",second);
    // Find the length of first and second string
    flength=strlen(first);
    slength=strlen(second);
    s=flength-slength;
    // find the difference between two strings
    if(s!=0)
    {
            printf("\n Enter the both digits are same ");          
    }
    // if both strings length are same then execute the following code
   else
   {
            for(i=flength-1;i>=0;i--)
           {      
                           // convert character to integer
                            fdata=(int)first[i]-48;
                           sdata=(int)second[i]-48;
                          // addition of two numbers
                           ans=remain+fdata+sdata;
                         // find the remain it will goto next step (1 or 0)
                           if(ans>=10)
                          {
                                      ans=ans-10;
                                      remain=1;          
                          }
                         else
                         {
                                     remain=0;
                         }
                         if(i==0)
                        {
                                    r1=remain;    
                        }
                        // answer back store as a character in second arrary
                       // because reduce memory occupation here use second input also used for
                      // output storage variable
                   
                       second[i]=(char)ans+48;
                               
         }         
     // print the answer
     printf("Answer : %d%s",r1,second);
   
  }  
 getch();
}

No comments:

Post a Comment