Hi guys. So in my introduction to programming class, we have to do a recursive function to find out if a number is even or odd, but without using any math.
This is the model answer given:
int even (int x)
{
if (x == 0)return 1;
return !even(predecessor(x));
}
Can someone explain to me what the ! means, and how this recursion works?? I can't seem to figure it out:( Thanks guys!
oh man. i'm still confused.
here's the whole code:
int even (int x)
{
if (x == 0) return 1;
return !even(x-1);
}
int main ()
{
int x;
scanf("%d", &x);
if (even(x))
printf("even/n");
else
printf("odd/n");
return 0;
}
let's say the input is 3, so what would the function return the first round? and does it return it to the main or to the function again?
when x finally equals 0, how does this information relate to your input number?
Let's say the input is 3. Here's how the call stack would unwind and give you the correct result false. However, it assumes that you change the definition of 'even' to use the bool type, like this:
1 2 3 4 5
bool even (int x)
{
if (x == 0) returntrue;
return !even(x-1);
}