As the code is very small, you can predict the output by walking through the program physically, or you could use a debugger to step through.
Main is the entry point of your program; So the very first line that you should start with is std::count<<funct(5)<<std::end1;
.
You enter the func(int x)
method with an initial parameter x of 5. This function looks at the parameter and returns 2 or 3 if x is 0 or 1, respectively. Otherwise, it will recursively call itself, returning the sum of func(x-1)
and func(x-2)
.
Stepping through you get the following execution order:
func(5)
func(4)
func(3)
func(2)
func(1)
return 3
func(0)
return 2
func(1)
return 3
func(2)
func(1)
return 3
func(0)
return 2
func(3)
func(2)
func(1)
return 3
func(0)
return 2
func(1)
return 3
Which translates to -> 3 + 2 + 3 + 3 + 2 + 3 + 2 + 3 = 21
If you aren't too familiar with recursion in programming, the concept should already be vaguely familiar. You almost certainly have come across the
Fibonacci Sequence, where the next number in the sequence is the sum of the previous two (with the first two numbers of the sequence defined as 0 and 1). The program you presented is very similar to the Fibonacci Sequence, however, it uses 2 and 3 as the first two numbers.
Hence, if you define the recursive sequence as a0 = 2, a1 = 3
, then an = an-1 + an-2
, which looks very similar to the function defined.