Erik Hambardzumyan Erik Hambardzumyan - 2 months ago 15
Javascript Question

Making a star triangle using javascript function recursively

I am pretty new to programming, I am getting to know JavaScript, and I've just learned the notion of recursion. Now I am given a problem, to create a function (like

const f = function(n) { }
) and if we if we call the function with
f(5)
, we should see:

*
***
*****
*******
*********


The number of vertical stars must be determined by the input.
I've got to use no for/while/do-while; recursion only to loop.

I've come up with this code to concatenate 5 stars

const f = function(n) {
if (n === 0) {
return "";
}
return "*" + f(n - 1);
};

console.log(f(5));


Though, I don't see how to make the triangle, what can I do?

Answer

You can use this code:

const f = function(chr, n) {
  if (n === 0) {
    return "";
  }
  return  chr +  f(chr, n - 1);
};
const g = function(n, max) {
   if (n > 1) {
      g(n-1, max);
   }
   console.log(f(' ', max-n) + f('*', (n*2)-1));
};
g(5, 5);

Comments