Write a function in c that takes 2 numbers in string and forms a string containing the addition of these 2 numbers?

140 views

Assumption:
The input strings will contain only numeric digits
The input strings can be of any large lengths
The lengths of the two input string need not be the same
The input strings will represent only positive numbers
Example

If input strings are “1234” and “56”, the output string should be “1290”
If input strings are “56” and “1234”, the output string should be “1290”
If input strings are “123456732128989543219” and “987612673489652”, the output string should be “123457719741663032871”

posted Sep 1, 2017

+1 vote

I believe what you need is two function integer to string and string to integer. First take two input as string convert them into integers add these two integers and convert the resultant to the integer and show.

``````#include <stdio.h>
#include <math.h>
#include <string.h>

void tostring(char str[], int num)
{
int i, rem, len = 0, n;

n = num;
while (n != 0)
{
len++;
n /= 10;
}
for (i = 0; i < len; i++)
{
rem = num % 10;
num = num / 10;
str[len - (i + 1)] = rem + '0';
}
str[len] = '\0';
}

int toint(char str[])
{
int len = strlen(str);
int i, num = 0;

for (i = 0; i < len; i++)
{
num = num + ((str[len - (i + 1)] - '0') * pow(10, i));
}

return num;
}

main()
{
char a1[]="10";
char a2[]="20";
char a3[5];

int b1, b2, b3;

b1 = toint(a1);
b2 = toint(a2);

b3=b1+b2;

tostring(a3,b3);

printf("%s\n", a3);
}
``````

Let me know if looking something more then this.

i cant understand the code.can you pls give the code completely.
I have updated the code, treat it as sample code only.
i understood the code,but the thing is when i gave a1=1234,a2=56 im getting the output as 1289.But the actual o/p is 1290.
And if i gave a1=45678,a2=295 im getting o/p as 45971,but the actual o/p is 45973..

so what has went wrong????
I checked with a1=1234 and a2=56 and getting the correct answer as 1290. Check the following link -
https://ideone.com/Y5xQxt
Thank you so much bro
Similar Questions

Assumption:

• The input strings will contain only numeric digits
• The input strings can be of any large lengths
• The lengths of the two input string need not be the same
• The input strings will represent only positive numbers

Example

If input strings are “1234” and “56”, the output string should be “1290”
If input strings are “56” and “1234”, the output string should be “1290”
If input strings are “123456732128989543219” and “987612673489652”, the output string should be “123457719741663032871”

It was asked today in interview but could not crack it, any help.

Let us assume the word is `“Hello World!!”`