Loading....
Coupon Accepted Successfully!

 

Recursion With Template Functions

Similar to normal function and member function, the template function also supports the recursive execution of itself. The following program illustrates this:
 
17.12 Write a program to invoke template function recursively.
#include<iostream.h>
#include<conio.h>
#include<process.h>
#include<stdlib.h>
#include<assert.h>
template<class O>
void display (O d)
{
cout<<(float) (rand()%(d*d))<<ā€œ\nā€;
// if (d==1) exit(1);
assert(d!=1);
display(--d);
}
void main()
{
int x=10;
clrscr(),
display(x);
}
OUTPUT
46
49
38
12
28
17
11
7
0
0
Assertion failed: d!=1, file REC_TEMP.CPP, line 14
Abnormal program termination
 

Explanation: The template function generates a random number and displays it each time the function display() is invoked. The function rand() defined in stdlib.h is used. The function calls itself recursively until the value of d becomes 1. The assert() statement checks the value of d and terminates the program when the condition is satisfied. The assert() is defined in assert.h. We can also use the if statement followed by the exit() statement as given in the comment statement.





Test Your Skills Now!
Take a Quiz now
Reviewer Name