Friday, July 13, 2018

Fibonacci Numbers

Problem statement:

Program to print first n Fibonacci Numbers


public class Test {
    // Method to print first n Fibonacci Numbers    static void printFibonacciNumbers(int n) {
        int f1 = 0, f2 = 1, i;
        if (n < 1)
            return;
        for (i = 1; i <= n; i++) {
            System.out.print(f2 + " ");
            int next = f1 + f2;
            f1 = f2;
            f2 = next;
        }
    }
    public static void main(String[] args) {
        printFibonacciNumbers(7);
    }
}
Output:
1 1 2 3 5 8 13

No comments:

Post a Comment

Blueprint for self-improvement

To learn faster: Make the process fun To understand yourself : Write To understand the world better : Read To build deeper connection : Lis...