SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Walter Savitch ,julia Lobur
Chapter:
Recursion
Exercise:
Self-test Exercises
Question:1 | ISBN:9780321531346 | Edition: 7

Question

What is the output of the following program?

#include <iostream>

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);

}

}

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

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:

  • This method takes n value is 3 and verify the loop condition.
  • Verify the "if" condtion is first, if n is not equal to 1, then go to
  • "else" condtion. So, first print "Hip", then call, cheers(n-1)=cheers(3-1)=cheers(2).
  • Now again if-else condition check to method cheers(2), it also go to print "Hip" again and then call, cheers(2-1)=cheers(1).
  • Now, again verify the if-else condition, if n is equal to 1, then print "Hurray" and exit the loop.

Finaly, display the output is: Hip Hip Hurray

0 0

Discussions

Post the discussion to improve the above solution.