Java - Print out numbers of fibonacci sequence.
In preparation for my Microsoft interview, I am going over some different ways to do the Fib sequence. Here is a simple iterative method to print out n fib numbers.
The interviewer could ask a number of questions from this point. E.x. Where might errors arise?
1. No cases defined for n=0, n=1, n=2
2. What if a non-number is given in input?
3. Negative number ?
4. What if a huge number is given in input? 99999999999?
These are all error-prone areas they will expect you to know to test.
public static void main(String[] args) { // TODO Auto-generated method stub Scanner s = new Scanner(System.in); System.out.println("Enter n:" ); int num = s.nextInt(); int n0 = 1, n1 = 1, n2; System.out.print(0 + " " +n0 + " " + n1 + " "); for(int i = 3; i < num; i++) { n2 = n1 + n0; System.out.print(n2 + " "); n0 = n1; n1 = n2; } }
The interviewer could ask a number of questions from this point. E.x. Where might errors arise?
1. No cases defined for n=0, n=1, n=2
2. What if a non-number is given in input?
3. Negative number ?
4. What if a huge number is given in input? 99999999999?
These are all error-prone areas they will expect you to know to test.
0 comments:
Post a Comment