In this example, you will use recursion to implement a method to print the ruler scale. The first is recursion, the function call itself is called recursion, recursive is very useful when it is necessary to divide a work into two smaller, similar work, recursive method is called divide-and-conquer strategy.
The following is a code for the Win32 console program:
1#include <iostream>2 3 using namespacestd;4 Const intLen = the;5 Const intDIVs =6;6 voidSubdivide (CharAr[],intLowintHightintLevel );7 intMain ()8 {9 CharRuler[len];Ten inti; One for(i =0; I < Len-2; i++) ARuler[i] =' '; -Ruler[len-1] =' /'; - intmax = Len-2; the intMin =0; -Ruler[min] = Ruler[max] ='|'; -cout << Ruler <<Endl; - for(i =1; I <= divs;i++) + { - Subdivide (ruler, Min, Max, i); +cout << Ruler <<Endl; A for(intj =0; J < Len-2; J + +) atRULER[J] =' '; - } - - return 0; - }; - in voidSubdivide (CharAr[],intLowintHightintLevel ) - { to if(Level = =0) + return; - intMid = (hight + low)/2; theAr[mid] ='|'; * //Recursive invocation $Subdivide (AR, Low, Mid, level-1);Panax NotoginsengSubdivide (AR, Mid, hight, level-1); -}
In this program list, the subdivide () function uses the variable level to control the recursive layer. When the function calls itself, the level is reduced by 1, and when level is zero, the function will no longer call itself. The subdivide function calls itself two times, once for the left half, and another for the right half, and the number of calls will also increase exponentially, that is, the call causes two calls at a time, and then causes four calls, which results in eight calls, and so on. This is why a 6-layer call can fill 64 elements (2 of 6 equals 64). This will constantly cause the number of function calls to be doubled, and this recursion will make a bad choice if the recursive hierarchy required is many, and recursive calls are appropriate for situations where the recursive hierarchy is less.
The method of using C + + to draw the ruler uses recursion