For example, if the number entered by the user is 4321
then, int array[0] = 1
int array[1] = 2
int array[2] = 3
int array[3] = 4
int array[4] = '\0' (End of array - when number == 0)
This is the piece of code i have written so far using a function called 'adddigits(int num)'. Once each digit is being stored into the array, the digit is being added to a variable to calculate the total sum of digits.
Please help me locate the problem and find a solution to store the individual digits into seperate successive array locations.
Expand|Select|Wrap|Line Numbers
- void adddigits(int num)
- {
- int i, length, a = 0, digsum = 0, digit[] = {'\0'};
- while(num!=0)
- {
- digit[a] = num % 10;
- printf("a value is: %d, ", a);
- printf("digit[a] value is: %d, ", digit[a]);
- digsum += digit[a];
- printf("sum is: %d, ", digsum);
- num /= 10;
- a = a+1;
- printf("length value is: %d, ", a);
- printf("\n");
- }
- printf("\n\ndigit[0] = %d", digit[0]);
- printf("\ndigit[1] = %d", digit[1]);
- printf("\ndigit[2] = %d", digit[2]);
- printf("\ndigit[3] = %d\n\n", digit[3]);
- }
The display (result) screen shows me the following and I absolutely don't have a clue as to why value of a changes to 4 after 2.
**** Display Screen (Output) ****
Enter a number whose sum of digits you require: 4321
a value is: 0, digit[a] value is: 1, sum is: 1, length value is: 1,
a value is: 1, digit[a] value is: 2, sum is: 3, length value is: 2,
a value is: 2, digit[a] value is: 3, sum is: 6, length value is: 3,
a value is: 4, digit[a] value is: -1, sum is: 5, length value is: 5,
digit[0] = 1
digit[1] = 2
digit[2] = 5
digit[3] = 5
Please assist me with this. Thanks.