I have faced the following interview question.
Consider this function declaration:
void quiz(int i) { if (i > 1) { quiz(i / 2); quiz(i / 2); } writeOutput("*"); }How many asterisks are printed by the function call
quiz(5)?
My answer was:
Languages (Javascript, PHP, etc.) with integer division result type is
float – seven asterisks. Function quiz get called:
- With i=5 – once, asterisk printed.
- With i=2.5 – twice, asterisks printed.
- With i=1.25 – four times, asterisks printed.
- With i=0.625 – eight times, no asterisks printed
Languages (C/C++, C#, Java, etc.) which division result type name is
integer – three asterisks. Function quiz get called:
- With i=5 – once, asterisk printed.
- With i=2 – twice, asterisks printed.
- With i=1 – four times, asterisks not printed.
Question syntax is like C/C++, Java, so the answer would be three
The interview was a closed book exam – during the interview I was unable to run this code and check it. The interviewer told me that my answer is not absolutely correct (or at least, they didn’t expect it to be like this). Hovewer, I’ve ran this code (with PHP, Javascript and C#) at home and the result was as I described.
So, are there some caveats I’m missing or my answer was just more detailed than they were expecting?
If you change the code to this:
You’ll see that the result for
quiz(5)is:So, you got the correct number of calls per i, you just didn’t notice that the writeOutput is outside the if, not inside it.