I need help understanding this. I really don't understand this piece of code and could someone here explain exactly what happens?
So this is the code:
static bool IsEven(int n)
{
if (n == 0) return true;
if (IsEven(n - 1))
{
return false;
}
else
{
return true;
}
}
And then I do this:
Console.WriteLine(IsEven(10));
How does it actually work? If I enter in number 10, it prints out true. If I enter number 7, it prints out false. But I don't understand why it even works.
It checks if the number is 0, then it returns true. But I entered 10 (which clearly is not 0) and it still print out true. Then it checks number -1.
So that would be 10-1, which is 9. But how does it know that 9 is NOT even? (it returns false).
I don't understand this code, but it works. I am so confused honestly.
Aucun commentaire:
Enregistrer un commentaire