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);
}
}
}
The most Pythonic way to check if a list has an even number of elements is to use the modulo expression len(my_list)%2 that returns 1 if the list length is odd and 0 if the list length is even. So to check if a list has an even number of elements use the expression len(my_list)%2==0 .
In computer science, recursion is a programming technique using function or algorithm that calls itself one or more times until a specified condition is met at which time the rest of each repetition is processed from the last one called to the first.
8) Which is the common problem with Recursive methods in Java? Explanation: StackOverError occurs when the stack has been full and can not allocate space for continuing new method call.
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
Working example here
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With