Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursive function to check if all digits in an int variable are even

Tags:

c

recursion

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);
        }
    }
}
like image 643
Gavin Avatar asked Feb 25 '15 07:02

Gavin


People also ask

How do you recursively check if a number is even?

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 .

What is recursive technique?

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.

What is the common problem with recursive methods in java?

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.


1 Answers

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.

like image 151
Mohit Jain Avatar answered Oct 03 '22 07:10

Mohit Jain