What is the output of the following program?
using namespace std;
void cheers(int n);
int main( )
{
cheers(3);
return 0;
}
void cheers(int n)
{
if (n == 1)
{
cout << "Hurray\n";
}
else
{
cout << "Hip ";
cheers(n − 1);
}
}
The output of the program:
Commented program:
//Header section
#include <iostream>
using namespace std;
//Function prototype
void cheers(int n);
//main program
int main( )
{
//Call the method
cheers(3);
return 0;
}
//Function "cheers" accept an integer parameter value of n
//and check the if-else condition to loop the parameter
//value and print result on screen
void cheers(int n)
{
//IF parameter value is equal to 1, then print
//'Hurry' or print 'Hip' then next recursion Call
//cheers.
//This loop ends the parameter value is equal to 1
if (n == 1)
{
cout << "Hurray\n";
}
else
{
cout << "Hip ";
cheers(n-1);
}
}
Explanation:
Call the method, cheers with parameter value is 3 in main() function.
The following points are verify the cheers method:
Finaly, display the output is: Hip Hip Hurray