#4 Interview Preparation | 'Code comprehension' series
What is the purpose of this article ?
The ‘Code comprehension’ series is aiming to prepare programmers to corporate coding interviews where they can be requested to read, explain and answer questions about a piece of code. This article is aiming to proceed in a similar way and is addressed primarily to the following people :
- People preparing for coding interviews
- People willing to evaluate their coding skills
Additionally information :
- The difficulty of this challenge is ranked as : Beginner
- The topic of this challenge is categorized as : Algorithm
- Programming language : JavaScript
Question #1
Given the below function f(…), what is the returned value when evaluating f(10, 0) ?
Solution
Note : Readers willing to answer this coding question by themselves should stop reading here. Below this point, the solution will be discussed and the answer will be provided.
As you can see, the function f(…) is recursive and takes two input integer parameters. To better see what it computes, lets breakdown the evaluation of f(10, 0).
The function f(x, a) is a recursive function summing the numbers from 1 to x (1 + 2 + 3 + … + x). This sum is also called the Gaussian sum. The second parameter a is called an accumulator and is used to store the intermediate results. The final result of the evaluation of f(10, 0) is 55.
Question #2
Is it possible to change the code of the function f(…) such that it does not use the parameter a ?
Solution
Note : Readers willing to answer this coding question by themselves should stop reading here. Below this point, the solution will be discussed and the answer will be provided.
Yes it is possible, solution below :