Download presentation
Presentation is loading. Please wait.
Published byPosy Hunt Modified over 9 years ago
1
Recursion in C++
2
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.
3
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
4
General algorithm for recursion if (terminal_condition) terminal_case else reducing_case if (!terminal_condition) reducing_case
5
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
6
The Factorial Function 5! = 5 * 4! 4! = 4 * 3! 3! = 3 * 2! 2! = 2 * 1! 1! = 1! * 0! 0! = 1 - Terminal Case Reducing Case
7
Recursive Factorial Function in C++ int fact(int n) { if (n < 2) // terminal case return 1; else // recursive step return (n * fact(n - 1)); }
8
#include 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); }
9
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
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.