I need to find the sum of the digits of a number with five digits. For example, the sum of the digits of the number 3709
is 3 + 7 + 0 + 9 = 19
.
#include <stdio.h>
int main()
{
int sum;
char digit_1, digit_2, digit_3, digit_4, digit_5;
printf("Plase enter a five digit number\n");
scanf("%c,%c,%c,%c,%c", &digit_1, &digit_2, &digit_3, &digit_4, &digit_5);
sum = digit_1 + digit_2 + digit_3 + digit_4 + digit_5;
printf("the sum of the digits is: %d", sum);
return 0;
}
output:
plase enter a five digit number
3709
the sum of the digits is 51
For some reason it doesn't show to correct answer and i can't seem to find whats wrong.
This works for many digits;
[By intention not a complete answer, but way to long for a comment]
A general rule applies: In case you feel a function fails to do what it should: Take a look at its documentation to learn if it would return any completion/error state. Here: Consult the value the
scanf()
function returns.Verbatim from
scanf()
s docs:Also during development it makes sense to add some debug output, to see what is really going on.
So your code could look like this:
Compile this with (most) all warnings on:
To fix the final error I leave to you. If done then just remove
-DDEBUG
from the compile options, which would exclude the (hopefully) enlighteningprintf
s. ;)The lesson learned may be: Checking for errors and logging is debugging for free.
The problem with your code is
your
scanf
needs,
separated inputsHence when you enter 3709 only
digit1
will be read and rest will be omitted byscanf
. You can check the return value ofscanf
to verify.and ASCII value of
3
is51
thus you are getting51
as output.Try this