Java program to print Fibonacci sequence using array

This java program will print fibonacci sequence up to given number.

if input is 5 then the program print 0 1 1 2 3

<pre>import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
 * java program to print fibonacci sequence
 * Created by Sani Kamal on 05-May-17.
 */
public class FibonacciSequence {
    public static void main(String[] args) {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        try {
            System.out.println("Enter the number of item to be printed: :");
            int num = Integer.parseInt(br.readLine());
            num = num > 2 ? num : 2;
            int[] fibArray = new int[num];
            fibArray[0] = 0;
            fibArray[1] = 1;
            for (int i = 2; i < num; i++) {
                fibArray[i] = fibArray[i - 1] + fibArray[i - 2];

            }
            System.out.println("Fibonacci Sequence..");
            for (int i = 0; i < num; i++) {
                System.out.print(fibArray[i]+" ");

            }


        } catch (Exception e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
    }
}</pre>
Advertisements

One thought on “Java program to print Fibonacci sequence using array

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s