Printing to the Screen a Recursive Half-Hourglass Pattern in C++?

I have to write a method printPattern(int num) such that a call to printPattern(4), for example, would output the following to the screen:

****

***

**

*

**

***

****

This must be done using recursion. I can get it to do the up to and including the single asterisk line, but after that I can't think of any way to print the other half without infinitely recursing and printing up to really huge lines of asterisks.

Any help would be appreciated (you can give example code if you want, or just conceptual help, I just can't think of any way to do this). Thanks.

Update:

Note: Iteration can be used to produce each individual line of asterisks, but for the overall pattern I have to use recursion.

1 Answer

Relevance
  • Anonymous
    1 decade ago
    Favorite Answer

    It's actually easy just not obvious. once you get to the recursive call at the end of the function, print a line of asterisks again. basically copy and paste your code for printing a line so you have two and put the recursive call in the middle. that way, for printPattern(4) it will print four lines, then recursive call, then print 3 lines all the way down to one, and then each function will finish executing by printing the line again. should look something like this:

    if (x==1)

    print a single asterisk

    for loop printing line

    recursive call

    identical for loop

Still have questions? Get your answers by asking now.