Thursday, 26 May 2011

Programming questions in Technical round2

1.Write a function that returns the factorial of a number. 
This is a typical, can-you-program warm-up question. Example 1 shows the iterative and recursive solutions. Notice that in both solutions, I check the input values and boundary conditions. Factorials of negative numbers are undefined, and the factorial of both 0 and 1 are 1. The functions in Example 1 handle these cases correctly, and they initialize all variables.
2.Write a function that computes the nth number in the Fibonacci sequence.
Example 2 contains both the iterative and recursive solutions. The iterative version maintains variables to hold the last two values in the Fibonacci sequence, and uses them to compute the next value. Again, boundary conditions and inputs are checked. The 0th number in the Fibonacci sequence is defined as 0. The first number in the sequence is 1. Return -1 if a negative number is passed.
The recursive version of the Fibonacci function works correctly, but is considerably more expensive than the iterative version. There are, however, other ways to write this function recursively in C that are not as expensive. For instance, you could maintain static variables or create a struct to hold previously computed results.

No comments:

Post a Comment