Does anyone know if a function is supposed to end after it returns something? I have my recursion function written below, but whenever it reaches the else statement and after it returns a value (steps),
it runs the "if (new_number % 2 == 1)" statement,
which does not make sense since the function should end when it reaches the else statement and should not repeat.
It works fine until it returns "steps" for the first time.
This is what happens after the first return: It doesn't even fully run the "if (new_number % 2 == 1)" statement, it just jumps to that line and decreases the value of "steps" and "input_steps" by 1. "new_number" and "number" just get completely random values
Then it returns "steps", then it jumps to "if (new_number % 2 == 1)" statement and decreases the value of "steps" and "input_steps" by 1. "new_number" and "number" just get completely random values again.
It repeats that cycle until "new_steps" and "steps" equal 0, then it returns 0 (because "steps" = 0) and ends the function.
Does anyone know why it does this????
Here is my code:
int step_recursion(int number, int input_steps)
{
int new_number = number;
int steps = input_steps;
if (new_number != 1)
{
if (new_number % 2 == 0)
{
if (new_number != 1)
{
step_recursion(new_number / 2, steps + 1);
}
}
if ((new_number % 2) == 1)
{
if (new_number != 1)
{
step_recursion(new_number * 3 + 1, steps + 1);
}
}
}
return steps;
}
I was expecting the function to end after returning "steps," but for some reason it doesn't. I already described the problem fully so go read that.