There are two core recursive algorithm:
1. The termination condition recursive recursive function return value and presence or absence of the return type setting function recursively determines the terminating condition
2. subproblems decomposed
Examples 1-- Tower of Hanoi problem
1 #include<iostream> 2 using namespace std; 3 void Hanoi(int n,char A,char B,char C){ 4 if(n==1) cout<<"MOVE top disk from "<<A<<" to "<<C<<endl; 5 else{ 6 Hanoi(n-1,A,C,B); 7 cout<<"MOVE top disk from "<<A<<" to "C << << endl; . 8 Hanoi (N- . 1 , B, A, C); . 9 } 10 } . 11 int main () { 12 is int n-; // Towers of Hanoi scale 13 is COUT << " Enter Tower of Hanoi your scale: " << endl; 14 the while ( 1 ) { 15 cin >> the n-; 16 IF (the n-< 1 ) cout << " Please check your input! " << endl; 17 the else BREAK ; 18 } . 19 char A, B, C; 20 is COUT << " Please enter the name of the three cylinder: " << endl; 21 is CIN >> A >> B >> C; 22 is Hanoi (n-, A, B, C); // call the function to solve 23 return 0 ; 24- }
Examples of the array and 2-- recursive solution
. 1 #include <the iostream> 2 the using namespace STD; . 3 int GetSum ( int n-, int * A) { // n-is the number of elements . 4 IF (n-== . 1 ) return A [ 0 ]; . 5 the else return GetSum ( N- . 1 , a) + a [N- . 1 ]; . 6 } . 7 int main () { . 8 int size; // size of the problem, namely the desired number of array elements . 9 COUT << " Please enter a question size: " << endl; 10 the while ( . 1 ) { . 11 CIN >> size; 12 is IF (size <= 0 ) << COUT " Please check the validity of the scale " << endl; 13 is the else BREAK ; 14 } 15 int * P = new new int [size ]; // dynamic open array 16 COUT << " Please enter the array elements in turn: " << endl; . 17 for ( int I = 0 ; I <size; I ++ ) { 18 is CIN >> * (P +I); . 19 } 20 is COUT << " given to each array element and: " << endl << GetSum (size, P); 21 is return 0 ; 22 is }
Example 3-- maximum array recursive solution
. 1 #include <the iostream> 2 #include <math.h> . 3 the using namespace STD; . 4 int getMax ( int n-, int * A) { // n-number of elements is . 5 IF (n-== . 1 ) return A [ 0 ]; . 6 the else return max (getMax (N- . 1 , a), a [N- . 1 ]); . 7 } . 8 int main () { . 9 int size; // number of the scale of the problem, i.e. elements 10 COUT < < " Please enter the scale of the problem:" << endl; . 11 the while ( . 1 ) { 12 is CIN >> size; 13 is IF (size <= 0 ) << COUT " Please check the validity of the scale " << endl; 14 the else BREAK ; 15 } 16 int * P = new new int [size]; // dynamic array opened . 17 COUT << " Please enter the array element in turn: " << endl; 18 is for ( int I = 0 ; I <size; I ++ ) { . 19 CIN >> * (P + I); 20 is } 21 is COUT << " maximum value array you entered is: " << endl << getMax (size, P); 22 is return 0 ; 23 is }