- It is worth pausing at this point
and reflect a little bit about For Loops
and a different way to simulate
the execution of a For Loop.
As we saw earlier the For Loop
is most appropriate when you know
the exact number of repetitions needed,
and there are no other conditions.
The For Loop is not the best choice
when the halting conditions are dynamic
or when waiting for an event to occur.
Let's recall our previous discussion
on recursion when we first introduced
the concept of If as a means to stop
a Recursive Process.
Lets examine the following function.
We are still printing the even numbers
from any number k up to 100.
However we doing this recursively.
Our Recursive Call its essentially mimicking
the behavior of the For Loop
it's just not explicit about it.
We are starting the function with a given value.
We are repeating the call for the function
until the value of k reaches 100
in which case the function stops
and the rest of the program, if there is one,
continues execution.
This is not the best choice to loop.
It works, it's elegant, doesn't require an explicit loop.
However please recall that each time you
are using recursion for every Recursive Call
the function creates another copy of itself.
Eventually, it drains the computer resources,
particularly memory.
Lets proceed to an actual C example
and compare the For and e Recursive calls.
Let's look at an example that again prints
the even numbers between zero to 100
and this time we'll compare side by side
the use of the For Loop versus
the use of the Recursive Function.
Just like before we are listing
the even numbers using the same For Loop, unchanged.
We are not going to repeat that.
It works just like the previous example.
In Line 40 there is a Recursive Function
that again starts with a value of k
that's being received by the function externally, in main.
Except now we don't have an explicit loop.
We are simply calling the function Recursively
in Line 47 passing it the value of k+2.
K+2 if we start at zero would now be two,
and Line 47 will be updated
to four, six, eight, and so on.
It will be printed in line 46,
and if in line 45 the value reaches 100
the recursion stops.
Lets see how this works and then we'll
compare this a little bit further.
As you can see the results are identical.
All even numbers between zero and 100
and then all even numbers between zero and 100 recursively.
While recursion takes much more memory
for such a small number you haven't noticed any difference.
So you might be tempted to think
that it really doesn't matter.
Actually it does because if you were to use
a larger number of Recursive Calls
you might risk into running out of computer memory.
Your computer might crash, might lock up,
and you might necessitate a reboot.
While Recursion is elegant and it works,
use it with caution.