Gavin
Gavin

Reputation: 2824

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

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

Answers (3)

Mohit Jain
Mohit Jain

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

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.

Upvotes: 5

ars
ars

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

Vagish
Vagish

Reputation: 2547

Replace

int *result;

With

int result;

Upvotes: 0

Related Questions