mickifox@sbcglobal.net wrote:[color=blue]
>
> OK:
> Purpose: Using user's input and 3 recursive functions, construct an hour
> glass figure. Main can only have user input, loops and function calls.
> Recursive function 1 takes input and displays a sequence of spaces;
> recursive function 2 uses input to display ascending sequence of digits;
> likewise, recursive function 3 uses input to display descending sequence of
> digits.
>[/color]
May I suggest you forget the hourglass at the moment and simply concentrate
on the individual pieces. It's much simpler that way.
OK. Your assignment is to write a function (which must be recusive) to output
a given number of spaces.
The goal is: output a given number of spaces.
Q: When is this goal extremely simple to reach?
A: If the number of spaces to output equals 0. Because then the
function has to do nothing.
So lets start writing the function with what we know up to now:
void Spacing( int n )
{
if( n == 0 )
return;
Q: What about other numbers?
A: Those cases are much to hard for us, thus we take a lazy approach:
If the goal is to output n spaces, let us output 1 space and let us
call a function which outputs the remaining n-1 spaces.
Q: But which function should we call?
A: Well, there is function Spacing. This function claims to be able to
output n spaces, thus it must be simple for this function to output
n-1 spaces.
void Spacing( int n )
{
if( n == 0 )
return;
cout << " ";
Spacing( n-1 );
}
Q: That's it?
A: That's it!
See. In the recursive call there is always 1 subtracted from n.
So if we start out with a value of lets say 5 for n, what happens.
5 doesn't equal 0, thus the if is not taken.
1 space gets sent to cout, then function Spacing is called with an
argument of 5 - 1 -> 4. That function does:
send 1 space to cout
call function Spaceing with an Argument of 4 - 1 -> 3. That function does:
send 1 space to cout
call function Spaceing with an Arg. of 3 - 1 -> 2. That function does:
send 1 space to cout
call function Spacing with an Arg. of 2 - 1 -> 1. That function does:
send 1 space to cout
call function Spaceing with an Arg. of 1 - 1 -> 0. That function does:
the first if detects that the passed argument happens to be 0, thus
it simply returns
function returns
function returns
function returns
function returns
function returns
and the program returns to the called which called Spacing( 5 ). Now count
how many spaces have been sent to cout. They are exactly 5. Each invocation
of Spacing, with the exception of the last one, has output exactly 1 space.
The trick is the subtraction. By always subtracting 1, we make the number of
spaces to output smaller and smaller until we finaly hit 0. And this is our
simple case, we know how to deal with that: do nothing.
--
Karl Heinz Buchegger
kbuchegg@gascad.at