Home > Net >  How do I get this recursive function to work?
How do I get this recursive function to work?

Time:01-16

This code should print a string, letter by letter, using recursion, i.e., without loops (do, while etc.), using a function to call itself. But it does nothing.

let str1 = 'gggGGG';

function runString(str) {
  let n = 0;

  function loop(str, n) {
    if (n === (str.length - 1)) {
      console.log('This is the end');
    }
    else {
      console.log(str[n]);
      n  ;
      
      return loop(str, n);
    }
  }
}

console.log(runString(str1));

CodePudding user response:

You could check for the end of the string and return.

Then print the first letter and call the function again with the rest of the string.

function runString(string) {
    if (!string) return;
    console.log(string[0]);
    runString(string.slice(1));
}

runString('Miracle');

CodePudding user response:

All you need to do is just to invoke the function that you have created called loop inside runString function.

let str1 = 'gggGGG';

function runString(str) {
    let n = 0;
    function loop(str, n) {
        if (n === (str.length - 1)) {
            console.log('This is the end');
        }
        else {
            console.log(str[n]);
            n  ;
            
            return loop(str, n);
        }
    }
    return loop(str, n);
}

console.log(runString(str1));

CodePudding user response:

I used your own own code, but I removed the paramethers of the 'loop' function, so it used the paramethers of it's parent function; Then I called the function 'loop'.

function runString(str) 
{ 
  let n = 0;
  
  // Here i removed the paramethers of the loop function
  function loop() { 
      if (n===(str.length)) { 
        console.log('This is the end'); 
      } 
      else {
        console.log(str[n]);
        n  ;
        return loop();
      }
    }
  
  // Here I called the function to execute
  loop()
} 

runString("gggGGG");

  • Related