CS 107 - 7/15/15 factorial function: 5! int fact (int n) { int result = 1; for ( int i = 1 ; i <= n ; i++ ) { result = result * i; } return result; } int main() { int n; n = fact (7); cout << "Factorial of 5 is: " << fact(5) << endl; cout << "Factorial of 10 is: " << fact(10) << endl; Return the largest value from an array int getLargest (int arr[], int size) { int large = arr[0]; for (int i = 0 ; i < size ; i++) { if ( large < arr[i] ) large = arr[i]; } return large; } void getTwoLargest (int arr[], int size, int &l1, int &l2) { //only works if the largest value is not duplicated and // not at position 0 in the array // find the largest value l1 = arr[0]; for (int i = 0 ; i < size ; i++) { if ( l1 < arr[i] ) l1 = arr[i]; } // find the second largest value l2 = arr[0]; for (int i = 0 ; i < size ; i++) { if ( l2 < arr[i] && l1 != arr[i]) l2 = arr[i]; } } void getTwoLargestV2 (int arr[], int size, int &l1, int &l2) { // find the largest value l1pos = 0; for (int i = 0 ; i < size ; i++) { if ( arr[l1pos] < arr[i] ) l1pos = i; } l1 = arr[l1pos]; // find the second largest value if (l1pos != 0) l2pos = 0; else l2pos = 1; for (int i = 0 ; i < size ; i++) { if ( arr[l2pos] < arr[i] && l1pos != i) l2pos = arr[i]; } l2 = arr[l2pos]; } int main() { int array1[X]; // load values into array1 int val = getLargest (array1, X); int large1, large2; getTwoLargest ( array1, X, large1, large2); ------------------- factorial take 2 int fact2 (int n) { int result = 1; // count down from n to 1 for ( int i = n ; i >= 1 ; i-- ) { result = result * i; } return result; } Recursion - when a function calls itself. definition of Recursion: see recursion In recursion a base case is needed to stop the recursive calls. int fact3 (int n) { // base case if ( n == 1) return 1; else return fact3 (n-1) * n; } exponentiation int power ( int base, int exp) { int result = 1; for ( int i = 0 ; i < exp ; i++) result = result * base; return result; }