Creating a star triangle using javascript function recursively

I am new to programming, I am familiar with JavaScript, and I just learned the concept of recursion. Now I have been given a problem to create a function (e.g. const f = function(n) { }), and if we call the function c f(5), we should see:

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

The number of vertical stars should be determined by the input. I have to use no for / while / do -while; recursion only in a loop.

I came up with this code to combine 5 stars

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

 console.log(f(5));

Although, I don’t see how to make a triangle, what can I do?

+4
source share
4 answers

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);
Run codeHide result
+4
source

 if (n === 0) ...

f(n-1)

.

. string.repeat() .

, : - .

0

I came up with this, that's what I need

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

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

const line = function(n, all){
    if(n === all+1)
        return;

    console.log(space(all-n) + astx(2*n - 1));

    line(n+1,all);
};

const triangle = function(n){
    line(1,n);
};

triangle(5);
0
source

function recursiveStar(n){
if(n === 0) return 0;
recursiveStar(n - 1);
return console.log('*'.repeat(n));
}
recursiveStar(5)
Run codeHide result
0
source

Source: https://habr.com/ru/post/1655702/


All Articles