# What is the output after each recursive function call?

2 views (last 30 days)
Camden Nelson on 8 May 2023
Commented: Jonas on 8 May 2023
Consider the following code:
function [out] = myRecurfn(num)
if floor(num) == 0
out = 2
else
out = 4 + myRecurfn(num-1)
end
end
When the above function is called with myRecurfn(3.5), what is the value of the output variable? Show your work, by showing what is ‘out’ for every call of the function and then how the final value is reached.
Since the value of out is only given for floor(num) == 0 (i.e. when num = 0.5) does that mean that the output for all the calls up to this point would just be: out = 4 + myRecurfn(3.5-1), out = myRecurfn(2.5-1), out = myRecurfn(1.5-1), and then the first output is out = 2? I am confused what is meant by a function call in this case, or what the output should look like for each call.
Jonas on 8 May 2023
you are on the right way, but floor() does not mean -1 as you wrote. floor of 3.5 is 3, not 2.5.
floor calcultes the nearest smaller integer of the input if the input is not already integer
3.5 -> 3
2 -> 2
-1.5 -> -2
and so on

Stephen23 on 8 May 2023
"I am confused what is meant by a function call in this case,"
A function call is every time a function is called. Usually functions are called by a user, e.g. when you write
sin(pi)
in the command line you are calling the SIN function. Inside a recursive function, a function calls itself (but the meaning has not changed at all). Every time this line is evaluated:
out = 4 + myRecurfn(num-1)
the function is called... and theoretically might have an output (to which 4 is added). Your assignment asks for the values of each of those outputs. Use DISP to display the function outputs.
myRecurfn(3.5);
2 6 10 14
These ouput values correspond to input values of 0.5, 1.5, 2.5, and 3.5 respectively. Why are they in that order?: consider when the output values are defined: on the very first call (from you the user) is the output value already calculated? No, an actual number can only exist after all the recursive calls are complete... ditto every other call exept the deepest one. The deepest function call finally outputs a value, to which you add four, which can then be returned to its calling function (which happens to be itself)... etc.
function [out] = myRecurfn(num)
if floor(num) == 0
out = 2;
else
out = 4 + myRecurfn(num-1);
end
disp(out) % display the function output
end

### Categories

Find more on Whos in Help Center and File Exchange

R2023a

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!