You are on page 1of 1

Common Recursive functions

#include <iostream> using namespace std; // factorial (recursive) int fact(int n){ if (n==0) return 1; // fact(0)=1 return n*fact(n-1); // fact(n)=n*fact(n-1) } // fibonaccui (recursive) int fibo(int n){ if (n==0) return 1; // fibo(0)=1 if (n==1) return 1; // fibo(1)=1 return fibo(n-1) + fibo(n-2); // fibo(n)=fibo(n-1)+fibo(n-2) } // power (recursive) float power(float base, int exp){ if (exp==0) return 1; // power(base,0)=1 if (exp>0) return base * power(base,exp-1); if (exp<0) return (1/base) * power(base,exp+1); } // sum array (recursive) int sumArray(int *r, int start, int max){ if (start==(max-1)) return r[start]; // last element return r[start] + sumArray(r, start+1, max); // current element * the sum of the rest of the array } // get array max (recursive) int getArrayMax(int *r, int start, int max){ if (start==(max-1)) return r[start]; // last element int maxRest=getArrayMax(r, start+1, max); // max of the rest array if (r[start]>maxRest) // return the max number return r[start]; else return maxRest;

// testing functions int main(){ cout << fact(5) << endl; // 120 cout << fibo(4) << endl; // 5 cout << power(2,3) << endl; // 8 const int MAX=5; int arr[MAX]={1,5,3,0,9}; cout << sumArray(arr,0,MAX) << endl; // 18 cout << getArrayMax(arr,0,MAX) << endl; // 9 } return 0;

You might also like