Recursive Functions
And now prepare for something that will blow your mind.
Functions can call functions! Yes.. we already saw that, main
called square
function.
But what if you have a function fun
that calls fun
!??
That's right, it is possible and useful sometimes.
Let's write a recursive function that counts down from n
to 0
.
Steps:
- add a new function
countdown()
- add a new parameter
n
with type Integer - add a new
If
command with conditionx > 0
- output
n
in the true branch - call
countdown(n-1)
after it - call
countdown(5)
in the main
Run the program, it should display 5
, 4
, 3
, 2
, 1
in the output.
So, how does this magic work? When countdown
is called with argument 5
it prints it.
Then it calls itself (recursion) with a different argument n-1
which is 4
.
Then that invocation calls itself with 3
etc.
The most important part is the base case/termination condition.
That is the false
branch, this recursion must finish somehow.
So if the number reaches 0
, nothing will happen, and recursion ends there.
Note that you will probably need some time to chew this concept, so no worries if it "doesn't click" immediately.
Keep learning and coding! ;)