edited by
2,795 views
16 votes
16 votes
Consider the following function definition.
void greet(int n)
{
    if(n>0)
    {
        printf("hello");
        greet(n-1);
    }
    printf("world");
}

If you run $\textsf{greet(n)}$ for some non-negative integer $\textsf{n},$ what would it print?

  1. $\textsf{n}$ times "hello", followed by $\textsf{n+1}$ times "world"
  2. $\textsf{n}$ times "hello", followed by $\textsf{n}$ times "world"
  3. $\textsf{n}$ times "helloworld"
  4. $\textsf{n+1}$ times "helloworld"
  5. $\textsf{n}$ times "helloworld", followed by "world"
edited by

5 Answers

Best answer
8 votes
8 votes

Take n = 2: 

void greet(2)
{
    if(2>0)
    {
        printf("hello");
//print number 1
        greet(1);
    }
    printf("world");
//3rd time print
}
   
 
void greet(1)
{
    if(1>0)
    {
        printf("hello");
//print number 2
        greet(0);
    }
    printf("world");
//2nd time print
}
 
   
void greet(0)
{
    if(0>0) fail {}
    printf("world");
//1st time print
}

Output = hellohelloworldworldworld i.e. $n$ times hello and $n+1$ times world.

Correct Answer: $A$

edited by
2 votes
2 votes
By close examine we can see that if portion will run for n times where as else will run for n+1 times "+1" when value of integer n=0

so n times hello and n+1 times world
2 votes
2 votes

Let's take n=5 and dry run the given recursive function.

Tree will look like this and one can simply count the numbers. 

Answer:

Related questions

23 votes
23 votes
5 answers
1
13 votes
13 votes
1 answer
2
30 votes
30 votes
6 answers
3