Reputation: 27
I tried to add two character arrays or integer arrays. It works correctly only if the values in the array is of one digit. If one or both of the arrays have numbers with two digits I got the wrong answer.
Suppose
//n = 3
a1[n] = "1 2 3"
a2[n] = "4 5 6"
I used while loop to addition ...
while(sizeofarray > i)
{
result[i]= atoi(&12[i]) + atoi(&a2[i]);
i++;
}
And i got the correct answer.
But if
a1[n] = "1 10 20"
a2[n] = "4 5 6"
the addition result will be wrong.
What is the correct code to solve this problem. Or at least the idea.
Upvotes: 0
Views: 351
Reputation: 4664
Each "element" of a C string is a single character, not a "number" in the sense that "10" is one number. For example, these declarations are equivalent:
char a1[] = "1 10 20";
char a1[] = {'1', ' ', '1', '0', ' ', '2', '0', 0};
char a1[] = {49, 32, 49, 48, 32, 50, 32, 0};
/* The 0 at the end is the NUL terminator, which tells the C library
that the string ends at that point */
If you create a1
and a2
as arrays, you can add corresponding elements.
int a1[] = {1, 10, 20};
int a2[] = {4, 5, 6};
But I'm assuming that you have a need to parse them as strings, and you can't just create arrays directly, such as reading data from standard input (usually the keyboard) or from a file. I see you're using the atoi
function to convert a string to a number. But the atoi
function does not return how many digits it swallowed up. Thus i++;
will skip too few digits unless adding 1-digit numbers. Besides, using one variable (i
) to hold the index into both strings works only when the numbers in each string start at the same index, that is, when each element has the same amount of digits.
To fix this, you need to do two things:
a1
and a2
arrays. Each pointer would point to the part of the array that has already been read. This way, after reading two integers from each string, one pointer would point to the end of the "10" and the other to the end of the "5".strtol
function, which returns a pointer to the end of the part of the string that the function has read. You can then use this pointer to skip past the number, and then (manually) skip past whitespace until hitting the next digit (use isdigit
) or NUL terminator.Upvotes: 1
Reputation: 70979
You have an array of characters, and as such, the digits encoded within the string of characters are not recognized as numbers. This has the side-effect of your program not finding and aligning decimal places during the addition routine.
"10" + "3" would yeild something line "40" if you don't align the decimal places manually. Using arrays of ints would solve the problem as math routines will account for the decimal place alignment automatically for all math types.
To fix this issue, you need to perform a routine
Upvotes: 0