Wednesday, December 18, 2013

Write a program to print the 3rd fibonaci number in a given range. If the number doesn't fall in the given range then print 0.

Given two number 10 and 150, you should print the 3rd fibonaci number after 10. The fibonaci numbers after 10 are 13, 21, 34, 55, 89, 144. The third fibonaci is 34.

Given input
10
150
Expected output
34
Program:  
package com.ranga;
class FibonacciSeriesDemo
{
    public static void main (String[] args)
    {
        int first = 0, second = 1, fib = first + second, count = 0;
        int start = 10, end = 150;
        boolean found = true;
        while(fib < end && found) {
            fib = first + second;
            if(fib >= start) {
               count = count + 1;
               if(count == 3) {
                    found = false;
               }
            }
            first = second;
            second = fib;
        }
        if(!found) {
          System.out.println("Third Fibonacci Series Value: "+ fib);  
        } else {
          System.out.println("Third Fibonacci Series Value: "+ 0);
        }
      
    }
}
Output:
Third Fibonacci Series Value: 34
 Note: This program is asked one guy in Facebook.

2 comments:

Unknown said...

Throwing Compilation error

Unknown said...

Sorry I got it now ......