And now prepare for something that will blow your mind.
Functions can call functions! Yes.. we already saw that,
But what if you have a function
fun that calls
That's right, it is possible and useful sometimes.
Let's write a recursive function that counts down from
- add a new function
- add a new parameter
nwith type Integer
- add a new
Ifcommand with condition
x > 0
nin the true branch
countdown(5)in the main
Run the program, it should display
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
Then that invocation calls itself with
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! ;)