- Here's the solution to the challenge number two
in this chapter.
You were asked to write a simple recursive function
that given two numbers small and large
will recursively print all the numbers in between.
Let's take a look.
First, straightforward printf commands
to ask the user to enter a small number
then a large number.
We are storing those values in two int variables;
smallNum, and largeNum.
Let's look at the recursive function,
and then why we call it the way we do.
The recursive function is called listNumbers,
and has three parameters; small, large, and K.
Let's focus on Line 32.
The function recursively calls itself
with small+1 because at each call of the recursion,
I want to increase the number by one
so that I print in Line 30 the current number.
If I start with small equals 10,
Line 32 will add one, and will make it 11
which will be printed in Line 30 and so on.
Large is the upper bound that's used in Line 31.
Keep in mind that at every recursive call,
small increments by one.
Eventually, it will reach the value of large.
However, Line 31 has a little if statement
that guarantees that the function only calls itself
as long as small is less than large.
Eventually, as we keep adding ones to small,
small will equal large.
When that happen, the program no longer calls itself,
and it simply halts.
The last parameter of the recursive function is K.
K is simply used as a counter as it was required
in the challenge definition
so that we can print what is the current
recursive call.
If you look at Line 25, the initial call
to list numbers uses smallNum, largeNum, and one.
K is being initialized to one in Line 32.
When listNumbers calls itself,
K is incremented by one and, therefore,
it counts this step.
In Line 30, I am printing both the current step K,
and the current value of the number.
Let's put this to test,
and see what this program outputs.
First I'm going to enter a small number,
let's say 27.
Then, I'm going to enter a large number,
let's say, 76, Enter, and here it is.
At the first step, I'm printing 27
which is Step One.
The step increases due to K,
and it stops with the last one which is 76
after 50 steps.