help with my code

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:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#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;
}
}
Last edited on
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)
Last edited on
thanks a lot!
Topic archived. No new replies allowed.