Amazon Interview Question
Software Engineer in TestsTeam: Kindle
Country: United States
Interview Type: Phone Interview
You are right... because the value is of n is post-decremented, so n=10 is passed every time.
It's an infinite loop printing the same number that you fed the original call to MyFunction. Does not matter if the number is positive or negative. The postfix decrement returns the original n during evaluation, so you'll be stuck calling MyFunction(n) with the same value of n. And you'll never get to the second print due to the infinite loop, so the same number will be printed over and over and over again.
If n = 10 it will print 10 until it runs out of memory and produce a stack overflow error (infinite loop). The second println(n) is never used because of the post-decrement of (n) in the recursive method call. If it were --n then the result would be 10,9,8,7,6,5,4,3,2,1,0,1,2,3,4,5,6,7,8,9 which is n-1. 10 to 1 for the 1st print(n) and 0 to 9 for the second print(n). Recursive method calls makes copies the code saves them to memory. After the (if) statement returns true the copies are returned in reverse order, LIFO.
for non negative no. it show series of no as n n-1 ... 1 0 1 2 ... n-1... :)
for negative no. its will be an infinite loop...
why it is infinite loop? Sequence is like below...
-int_min...... -1 0 1 2 ...... +int_max
if you pass -ve number then it will reach -int_min and then it go to +int_max and then deceased and reach to 0 and then function will return
it will print as n n-1......2.1.1.2.....n-1.n but no 0
as d code says.
"if (n == 0)
return; "
doesn't matter its java or c++. it will be infinite loop and will throw an stack overflow exception.
Also one thing if its --n instead of n--, what do you think the output will be.
if its --n the output will be 10 9 8 7 6 5 4 3 2 1 0 1 2 3 4 5 6 7 8 9.
The reason is when first time (assuming n=5) myFunction(5) is called which stores 5 into the program stack. next call is myFunction(--n) i.e. myFunction(4) is called which creates value 4 in the stack. similarly it stores till 0. now when n == 0, the myFunction(0) returns and the next statement i.e. print(n) after the myFunction() in else gets executed. print(n) reads the last value in stack which is 1 and prints it, then this myFunction() returns and so print(n) gets executed which reads next value in stack i.e. 2. Similarly it does it for each value till 4. But when it prints 4, it reaches to the stack position containing element 5 but at that moment there wasn't any recursive call made and so it returns to main function without printing 5 in the last. So that's why it printed the above output.
Hope everyone got it what i meant to say. Everything is because of recursion.
In java, the same programe will give us the output , suppose if our input is n=10 means then the output will be 10 10 10 10 10 10 10 ... at last JVM will through the StackOverFlowException
- Beginner March 29, 2012