Answers for "how to make recursive function in javascript"

7

how to make recursive function in javascript

// Basic Recursive function
// It works in all languages but lets try with Javascript

// lets make a greedy factorial calculator

function my_recursive_factorial(nb) // nb to compute his factorial
{
  	if (nb < 0 || nb > 12) // error case
        return 0;
    if (nb == 1 || nb == 0)
        return 1; // you have to check limit for factorial
  
    return nb * my_recursive_factorial(nb - 1); // ! Recursive call !
}

//This will find factorial from 1 to 12 with recursive method

// Recursive functions are greedy and should be used in only special cases who need it
// or who can handle it.

// a function become recursive if she calls herself in stack
Posted by: Guest on August-09-2021
5

how to make recursive function

// Basic Recursive function
// It works in all languages but lets try with C

// lets make a greedy strlen

int my_recursive_strlen(int index, char *str) // note that index must be set at 0 to work in this case
{
  if (str[index] == '\0')
    return index + 1;
  else
    return my_recursive_strlen(index++); // i send index + 1 to next function call
  // this increment index in our recursive stack
}

void main(void)
{
  printf("length of Bonjour = %d\n", my_recursive_strlen(0, "bonjour"));
}

//output : length of Bonjour = 7

// Recursive functions are greedy and should be used in only special cases who need it
// or who can handle it.

// a function become recursive if she calls herself in stack
Posted by: Guest on August-09-2021

Code answers related to "how to make recursive function in javascript"

Code answers related to "Javascript"

Browse Popular Code Answers by Language