// 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] == ' ')
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
", 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
>>> def sum_digits(n):
"""Return the sum of the digits of positive integer n."""
if n < 10:
return n
else:
all_but_last, last = n // 10, n % 10
return sum_digits(all_but_last) + last
void recurse()
{
... .. ...
recurse();
... .. ...
}
int main()
{
... .. ...
recurse();
... .. ...
}
Please ask me about Recursive function gangcheng0619@gmail.com