/* This code works when the added chracter's value is less than or equal to 9. I mean when there is a carry,what will i do to print that. And there should not be used any library function. Run the program and you will understand clearly. */

#include "stdafx.h"
int strlen(char str[]);

int main()
{
    int i=0,len1,len2,max,min,j=0,k=0,l=0;
    char num1[30],num2[30],ans[50];

    gets_s(num1);
    gets_s(num2);

    len1=strlen(num1);
    len2=strlen(num2);

    if(len1>len2)
    {
        max=len1;
        min=len2;
    }
    else
    {
        max=len2;
        min=len1;
    }

    while(num1[i]!='\0')
        i++;

    j=max-1;

    while(j>=0)
    {
        num1[j]=num1[i-1];
        i--;
        if(i<0)
            num1[j]=48;
        j--;    
    }

    while(num2[k]!='\0')
        k++;

    l=max-1;

    while(l>=0)
    {
        num2[l]=num2[k-1];
        k--;
        if(k<0)
            num2[l]=48;
        l--;    
    }

    for(i=max-1;i>=0;i--)
        ans[i]=num1[i]+num2[i]-48;

    for(i=0;i<max;i++)
        printf("%c",ans[i]);

    printf("\n");
    return 0;
}


int strlen(char str[])
{
    int len=0;

    while(str[len]!='\0')
        len++;
    return len;
}

Recommended Answers

All 5 Replies

Hope this helps.

#include "stdafx.h"
int strlen(char str[]);
int toint(char);
char tochar(int);
int main()
{
    int i=0,len1,len2,max,min,j=0,k=0,l=0;
    int carry = 0 ;
    char num1[30],num2[30],ans[50];
    gets_s(num1);
    gets_s(num2);
    len1=strlen(num1);
    len2=strlen(num2);
    if(len1>len2)
    {
        max=len1;
        min=len2;
    }
    else
    {
        max=len2;
        min=len1;
    }
    while(num1[i]!='\0')
        i++;
    j=max-1;
    while(j>=0)
    {
        num1[j]=num1[i-1];
        i--;
        if(i<0)
            num1[j]=48;
        j--;
    }
    while(num2[k]!='\0')
        k++;
    l=max-1;
    while(l>=0)
    {
        num2[l]=num2[k-1];
        k--;
        if(k<0)
            num2[l]=48;
        l--;
    }

    for(i=max-1; i>=0; i--)
    {

        ans[i] =   tochar( ( toint(num1[i]) + toint(num2[i]) + carry ) %10) ;
        carry = ( toint(num1[i]) + toint(num2[i]) + carry ) / 10;

    }
    if(carry) printf("%d",carry);
    for(i=0; i<max; i++)
        printf("%c",ans[i]);
    printf("\n");
    return 0;
}
int toint(char a)
{
    return a - 48;
}
char tochar(int a)
{
    return a + 48;
}
int strlen(char str[])
{
    int len=0;
    while(str[len]!='\0')
        len++;
    return len;
}

In the line 54 is the condition to check whether there is a non zero carry generated from the addition of the leftmost digits, if it's true then the carry is displayed before the remaining part of the answer.

What's the error ?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.