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?
Here it is.
https://gateoverflow.in/179276/tifr2018-a-7
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$
Let's take n=5 and dry run the given recursive function.
Tree will look like this and one can simply count the numbers.
64.3k questions
77.9k answers
244k comments
80.0k users