Recursive Member Function
Like C, C++ also supports recursive feature; that is, a function is called repetitively by itself. The recursion can be used directly or indirectly. The direct recursion function calls to itself until the condition is true. In indirect recursion, a function calls to another function and then the called function calls to the calling function. Here, the recursion with member function is illustrated in the following program:
8.32 Write a program to calculate triangular number by creating a member function. Call it recursively.
Explanation: In the above program, class num is declared with one member function tri_num(). This function is used to calculate the triangular number of the entered number. The triangular number is nothing but the sum from 1 to the number entered. In function main(), a number is read through the keyboard and it is passed to function tri_num(), which is invoked by the object a of class num. The tri_num() is invoked and tri_num() invokes itself repetitively till the value of m becomes 0. The variable f holds the cumulative total of successive numbers and return() statement returns value of f in function main(), where it displays triangular number on the screen.