Consider this function declaration: void quiz(int i) { if (i > 1) { quiz(i / 2); quiz(i / 2); } cout << "*"; } How many asterisks are printed by the function call quiz(5)?
Answer: The first time, i = 5 which is greater than 1, so the
function is called twice with a value of (5/2) = 2. Since 2 > i,
the function is called 4 times with a value of 1, and is not called
anymore, since i <= 1.
This gives a total of 1 + 2 + 4 function calls, with one asterisk
being printed for each call. Therefore, 7 asterisks are
printed.
now my question is "Since 2 > i, the function is called 4 times with a value of 1" why quiz(2) is called 4 times? please explain me this. I am having confusion. I understand the when i is 5 quiz function is called 2 times because there are two recursive calls "quiz(i / 2); quiz(i / 2);"
It is because of the fact when you call the function for the first time * will be printed for one time and two recursive calls will be called with the value of 2 and for each recursive call with the value of 2 recursive function will be called two times with the value of 1 and two asterisk will be printed so when you call function with the value of 5 only 1 asterisk will be printed and for the value of 2 two instances will be called with the value of 2 and for the instances withthe value of 2 , the recursive function will be called for two times each so for the value of 2 , for the value of 2 , four instances will be called because we are calling two instances of recursive function in the quiz function and it recursive call will be keep on increasing in the multiple of two.
Get Answers For Free
Most questions answered within 1 hours.