Answers for "c recursion"

C
1

how to make recursive function in C

// 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.
Posted by: Guest on August-09-2021
0

c recursion

#include <stdio.h>

int fibonacci(int i) {

   if(i == 0) {
      return 0;
   }
	
   if(i == 1) {
      return 1;
   }
   return fibonacci(i-1) + fibonacci(i-2);
}

int  main() {

   int i;
	
   for (i = 0; i < 10; i++) {
      printf("%d\t\n", fibonacci(i));
   }
	
   return 0;
}
Posted by: Guest on May-28-2020

Code answers related to "C"

Browse Popular Code Answers by Language