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?
function createPyramid(rows) { for (let i = 0; i < rows; i++) { var output = ''; for (let j =0; j < rows - i; j++) output += ' '; for (let k = 0; k <= i; k++) output += '* '; console. log(output); } } createPyramid(5) // pass number as row of pyramid you want.
Recursion is when a function calls itself until someone stops it. It can be used instead of a loop. If no one stops it, it'll recurse forever and crash your program. A base case is a condition that stops the recursion.
You can use this code:
const f = function(chr, n) {
  if (n === 0) {
    return "";
  }
  return  chr +  f(chr, n - 1);
};
const g = function(max) {
   const inner = function(n) {
       if (n > 1) {
           inner(n-1);
       }
       console.log(f(' ', max-n) + f('*', (n*2)-1));
   };
   inner(max);
};
g(5);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With