Skip to content
Advertisement

Create a triangle out of stars using only recursion

I need to to write a method that is called like printTriangle(5);. We need to create an iterative method and a recursive method (without ANY iteration). The output needs to look like this:

JavaScript

This code works with the iterative but I can’t adapt it to be recursive.

JavaScript

I should note that you cannot use any class level variables or any external methods.

Advertisement

Answer

Notice in your iterative approach that you have two counters: the first is what line you are on line, and the second is what position on the line you are on x. You could create a recursive function that takes two parameters and uses them as nested counters, y and x. Where you decrement x until it reaches 0, then decrement y and set x = y, until both x and y are 0.

You could also notice that each successive line in the triangle is the previous line plus one star. If your recursive function returns a string of stars for the previous line, the next line is always that string plus one more star. So, your code would be something like:

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement