Home > Blockchain >  Can someone explain how can i transform a for loop to recursion
Can someone explain how can i transform a for loop to recursion

Time:09-09

Can someone explain how can I transform this for loop to recursion? Thank you so much in advance.

//FibonacciNumbers_v1
#include <stdio.h>
#define LIMIT 10
main() {
showFibonacciValues();
}
showFibonacciValues() {
int n;
long fn;
long fn1 = 1;
long fn2 = 0;
double q;
    for(n = 2; n <= LIMIT;   n) {
    fn = fn1   fn2;
    q = (double) fn / fn1;
    fn2 = fn1;
    fn1 = fn;
    printf("%7ldld).16f\n", n, fn, q);
    }
}

CodePudding user response:

You can do it this way:

#include <stdio.h>

int factorial(int n) {
   //base case
   if(n == 0) {
      return 1;
   } else {
      return n * factorial(n-1);
   }
}

int fibbonacci(int n) {
   if(n == 0){
      return 0;
   } else if(n == 1) {
      return 1;
   } else {
      return (fibbonacci(n-1)   fibbonacci(n-2));
   }
}

int main() {
   int n = 5;
   int i;
    
   printf("Factorial of %d: %d\n" , n , factorial(n));
   printf("Fibbonacci of %d: " , n);
    
   for(i = 0;i<n;i  ) {
      printf("%d ",fibbonacci(i));            
   }
}

CodePudding user response:

For recursive you can write that:

//FibonacciNumbers_v1
#include <stdio.h>
#define LIMIT 10
int main() {
    showFibonacciValues(2,0,1,0,0);
    return 0;
}
showFibonacciValues(int val, long fn, long fn1,long fn2,double q) {

    fn = fn1   fn2;
    q = (double) fn / fn1;
    fn2 = fn1;
    fn1 = fn;
    printf("%7ldld).16f\n\n", val, fn,q);
    
    if(val < LIMIT) {
        showFibonacciValues(  val,fn,fn1,fn2,q);
    }
}
  • Related