0 Members and 1 Guest are viewing this topic.

/*rafy recursion example 1 */#include <stdio.h>void recurse (int count){ if (count<9) /*We need a limit otherwise the program would execute till it crashes*/ { printf("%d \n",count); /*prints the count on-screen*/ recurse (count +1); /*calls the function recurse and adds 1 to the count*/ }} int main (){ recurse (1); /* the first time I call the function I put count=1 */ return 0;}

#include <stdio.h>#include <stdlib.h>int f(int n){ if(n<=2) return n; else return n * f1(n-1);}int main(){ printf("Factorial of 10: %i\n", f(10)); return 0;}

int fact(unsigned int n){ if (n<=2) return n; unsigned int answer = 1; while (n != 1) answer *= (n--); return answer;}

Be careful with recursive functions, since for every function call a separate stack frame is made. This can lead to segmentation fault Instead you can use a loop to do stuff like finding a factorial:Code: [Select]int fact(unsigned int n){ if (n<=2) return n; unsigned int answer = 1; while (n != 1) answer *= (n--); return answer;}

So here it goes for now.I know tail recursion is missing

Be careful with recursive functions, since for every function call a separate stack frame is made. This can lead to segmentation fault Instead you can use a loop to do stuff like finding a factorial:

Yours is a tail recursion.