Reputation: 2824
I am trying to write a recursive function to check whether a user input a number which contains all even digits.
What is wrong with my logic? When I tried with "556" result is 1.
int main()
{
int num;
int *result;
printf("Enter a number: ");
scanf("%d", &num);
allEven(num, &result);
printf("allEven(): %d", result);
}
void allEven(int number, int *result)
{
if ((number % 10) % 2) // if the last digit is odd
{
*result = 0;
}
else
{
*result = 1;
if ((number / 10) != 0) //not the last digit to evaluate, we call the function again.
{
allEven((number / 10), &result);
}
}
}
Upvotes: 5
Views: 4799
Reputation: 30489
allEven((number / 10), &result);
should be replaced with
allEven((number / 10), result);
Because allEven
expects second argument of type int *
and &result
is int **
Also int *result
should be int result = 1
If you compile with proper warning flags -W -Wall
for example on gcc (better with -O2
), you should get proper warnings to correct your code.
Upvotes: 5
Reputation: 707
You should write it down this way to compile the code:
void allEven(int number, int *result)
{
if ((number % 10) % 2) // if the last digit is odd
{
*result = 0;
}
else
{
*result = 1;
if ((number / 10) != 0) //not the last digit to evaluate, we call the function again.
{
allEven((number / 10), result);
}
}
}
int main()
{
int num;
int result;
printf("Enter a number: ");
scanf("%d", &num);
allEven(num, &result);
printf("allEven(): %d", result);
}
1) "int* result" replace with "int result"
2) "allEven((number/10), &result)" call in main() replace with allEven((number/10), result)
3) you missed a brace in allEven function
Upvotes: 3