i tried to write a program that ask for number (int) and digit (char) and brings back how many time the digit appears in the number.
for example: the user put 1231, 1
and the program bring back 2.
the program also check whether the char is a digit between 0-9. if not, it should bring back -1.
please tell me what is the problem with my code.
that my code:
#include <stdio.h>
int countDigits(int n, char c)
{
int x=0, result;
if ('0' >= c || c >= '9');
return -1;
for (result=0; n>0;)
{
result=n % 10;
n=n/10;
if (result == c)
x= x+1;
}
return x;
}
int main ()
{
int digit, num;
printf("please enter a number and a digit:\n");
scanf("%d,%d", &num, &digit);
printf("%d\n", countDigits(num,digit));
return 0;
}
}
The characters '0'-'9' does not have the integer values 0-9, more likely 48-57 (in ASCII). It's probably better to keep the digit as an int at least until you have checked that it's inside the correct range. if (0 >= c || c >= 9) // and don't put a semicolon here!
On line 14 you want the variable c and not the character c, so remove the quotes. if (result == c)