> Recursion java?

Recursion java?

Posted at: 2014-12-18 
I think you're on the right track. To help you move forward:

Consider this: The argument to the top-most printStars function is both the number of stars and the WIDTH of a line that we're printing. While the program runs, we'll be printing different numbers of stars, but always the same line width. (Just an observation that might be useful later, & I wouldn't be surprised if you've already made the observation yourself.)

The top-most printStars could work like this:

void printStars (int n) {

if (n < 0) { /* nothing */ }

else {

printOneLine (???????); /* could be your helper func */

printStarts (n - 1);

}

}

But what arguments for the helper function? It needs to know the number of stars and the number of dashes (or the number of stars and the width of the line). Sounds like we need another helper. Here's a new printStars plus a helper for it:

/* top-level interface */

void printStars (int n) { loopOverLines (0, n); }

/* Call the line-printer for increasing star counts */

void loopOverLines (int stars, int width) {

if (width <= stars) {

/* Most people would RETURN here, but I can't, I just can't(!)

* return out of the middle of a function. So I use empty

* blocks. Change it to suit your style. */

} else {

printOneLine (stars, width - stars);

loopOverLines (stars + 1, width);

}

}

Now we need the printOneLine function. If you do it recursively, it'll need to check both of its arguments. As long as there are stars to print, it prints a star & calls itself with a smaller star count. Otherwise, it prints a stripe & calls itself with a smaller stripe count. And of course it checks to see if it's done first.

Howeer, the thought occurs that, if the maximum number of stars isn't too large, you could hard-code a big string of stars & strips into your program, maybe like this:

private String big = "**********----------";

... but probably much longer. Has maximum number of stars followed by same number of stripes. Then your print-one-ine function can print the substring from that which has the correct total length, correct number of stars, followed by the correct number of stripes. No loops! :)

(Interestingly, some programming languages don't offer iteration. The only way to loop in them is via recursion. Examples are Erlang, Haskell (I think), & Standard ML (I think).)

Alright, got it I guess:

http://ideone.com/4y6Ip7

No loops allowed!

i have to implement the method

void printStars(int n)

to print out

---

*--

**-

***

(when n=3)

one of the helpers i came up with is

private void printStars(int stars, int stripes)

Im not sure how to go about this. Do i need another helper? or can i just use the one i came up with. Im not so sure what to do.