680 likes | 1.75k Views
Recursion in C++. Recursion. Recursive tasks: A task that is defined in terms of itself. A function that calls itself. With each invocation, the problem is reduced to a smaller task ( reducing case ) until the task arrives at some terminal case . Recursive Functions.
E N D
Recursion • Recursive tasks: • A task that is defined in terms of itself. • A function that calls itself. • With each invocation, the problem is reduced to a smaller task (reducing case) until the task arrives at some terminal case.
Recursive Functions • A recursive function has two parts: • the terminal/base case. • - a stopping condition • the reducing case/recursive step • an expression of the computation or definition in terms of itself
if (terminal_condition) terminal_case else reducing_case if (!terminal_condition) reducing_case General algorithm for recursion
The Factorial Function • n! = n * (n-1) * (n -2) * … * 2 * 1 • 5! = 5 * 4 * 3 * 2 * 1 • The same function can be defined recursively as fallows: • 0! = 1 – terminal case • n! = n * (n - 1)! - the reducing case
The Factorial Function • 5! = 5 * 4! • 4! = 4 * 3! • 3! = 3 * 2! • 2! = 2 * 1! • 1! = 1! * 0! • 0! = 1 - Terminal Case Reducing Case
Recursive Factorial Function in C++ int fact(int n) { if (n < 2) // terminal case return 1; else // recursive step return (n * fact(n - 1)); }
#include <iostream> #include <cstdlib> using namespace std; int sum_of (int ary [ ], int num); int main () { int ary [5] = {5, 10, 15, 20, 25}; int num = 5; int ans; ans = sum_of (ary, num); cout<<"\nThe sum of the elements of the array is "<<ans; system("pause"); return EXIT_SUCCESS; } int sum_of (int ary [ ], int num) { int sum; if (num == 0) { sum = 0; cout<<"nAt the ladder bottom - num is "<<num; } else { cout<<"\nDescending - num is "<<num; sum = ary [num - 1] + sum_of (ary, num - 1); cout<<"\nAscending - num is "<<num<<" sum is "<<sum; } return (sum); }
int ary [5] = {5, 10, 15, 20, 25}; Descending - num is 5 Descending - num is 4 Descending - num is 3 Descending - num is 2 Descending - num is 1 At the ladder bottom - num is 0 Ascending - num is 1 sum is 5 Ascending - num is 2 sum is 15 Ascending - num is 3 sum is 30 Ascending - num is 4 sum is 50 Ascending - num is 5 sum is 75