Coupon Accepted Successfully!


The main(), Member Function, and Indirect Recursion

When a function calls itself, then this process is known as recursion or direct recursion. When two functions call each other repetitively, such type of recursion is known as indirect recursion. Consider the following program and explanation to understand the indirect recursion using OOP. The program without using OOP is also described for programmers who are learning C++.

8.39 Write a program to call function main() using indirect recursion.

Explanation: In the above program, class rec is declared with constructor, destructor, member function pass(), and two integer variables. The integer variable j is private and f is public. The function main() is defined with one integer argument. Usually, main() with arguments is used for the applications on the dos prompt. In this program, main() is called recursively by member function pass(). When a function call is made, the value of member data variable is decreased first and then passed. Thus, the main() passes value to itself. In function pass(), main() function is invoked and its return value is displayed. The public data member is directly used and by applying multiplication operation, factorial of a number is calculated.

Generally, objects are declared inside the function main(). But in this program function main() is used in recursion. Hence, if we put the object declaration statement inside the main(), in every call of main() object is created and the program will not run properly. To avoid this, the object is declared before main().

Constructor is used to initialize data members as well as to clear the screen. Destructor is used to display the factorial value of the number. All the statements that we frequently put in main() are written outside of main().

Before the class declaration, prototype of main() is given, because the member functions do not know about; and the prototype declaration provides information about main() to member function.

Tip: For C programmers the previous program in C style is explained as follows.

8.40 Write a program to call function main() using in-direct recursion in C style.


Explanation: The logic of the program is same as the previous one. The user-defined function pass() has only one job to invoke function main(). The if conditions inside main() check the value of variable x. If value of x is zero, then if block is executed that displays factorial of the number and terminates the programs.

Test Your Skills Now!
Take a Quiz now
Reviewer Name