![]() |
VOOZH | about |
Question 1 : Explain the functionality of the following functions.
Answer: This function adds the sum of first x natural numbers to y. It repeatedly decreases x and adds its value to y until x becomes 0. Final result: y + (1 + 2 + ... + x) = y + x(x + 1) / 2. For example, if x is 5 and y is 2, then fun should return 15 + 2 = 17.
Question 2 : Explain the functionality of the following functions.
The above function calculates and returns ⌊log2(n)⌋. For example, if n is between 8 and 15 then fun1() returns 3. If n is between 16 to 31 then fun1() returns 4.
Question 3
Answer: The function fun2() prints the binary equivalent of n. For example, if n is 21 then fun2() prints 10101.
Question 4 : Predict the output of the following program.
fun(4);
/
fun(3), print(3), fun(2)(prints 0 1)
/
fun(2), print(2), fun(1)(prints 0)
/
fun(1), print(1), fun(0)(does nothing)
/
fun(0), print(0), fun(-1) (does nothing)
Explain the functionality of below recursive functions.
Question 5 : Predict the output of the following program.
Answer: Total numbers of stars printed is equal to 1 + 2 + .... (n-2) + (n-1) + n, which is n(n+1)/2.
Please write comments if you find any of the answers/codes incorrect, or you want to share more information about the topics discussed above.