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:
countdown()
n
with type IntegerIf
command with condition x > 0
n
in the true branchcountdown(n-1)
after itcountdown(5)
in the mainRun 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! ;)