0% found this document useful (0 votes)
14 views

Common Recursive

This document defines and provides examples of common recursive functions including factorial, Fibonacci, power, sum of an array, and maximum value of an array. The factorial function calculates n! recursively as n * (n-1)!. Fibonacci computes Fib(n) as Fib(n-1) + Fib(n-2). Power uses recursion to calculate base^exp. Sum array recursively sums all elements by adding each element to the sum of the remaining elements. Get array max recursively finds the maximum value by comparing each element to the max of the remaining elements.

Uploaded by

Ahmed Hosni
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Common Recursive

This document defines and provides examples of common recursive functions including factorial, Fibonacci, power, sum of an array, and maximum value of an array. The factorial function calculates n! recursively as n * (n-1)!. Fibonacci computes Fib(n) as Fib(n-1) + Fib(n-2). Power uses recursion to calculate base^exp. Sum array recursively sums all elements by adding each element to the sum of the remaining elements. Get array max recursively finds the maximum value by comparing each element to the max of the remaining elements.

Uploaded by

Ahmed Hosni
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 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