Program to print first n Fibonacci Numbers

1

Following is simple program to print first n Fibonacci numbers.

fibonacci-sequence

Examples :

Input : n = 3
Output : 1 1 2

Input : n = 7
Output : 1 1 2 3 5 8 13

C

// C program to print first n Fibonacci numbers
#include <stdio.h>

// Function to print first n Fibonacci Numbers
void printFibonacciNumbers(int n)
{
    int f1 = 0, f2 = 1, i;

    if (n < 1)
        return;

    for (i = 1; i <= n; i++)
    {
        printf("%d ", f2);
        int next = f1 + f2;
        f1 = f2;
        f2 = next;
    }
}

int main()
{
    printFibonacciNumbers(7);
    return 0;
}

Java

// Java program to print first n Fibonacci Numbers

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;
        }
    }    
    
    // Driver method
    public static void main(String[] args) 
    {
        printFibonacciNumbers(7);
    }
}


Output:
1 1 2 3 5 8 13

Time Complexity : O(n)

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geekforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

GATE CS Corner    Company Wise Coding Practice

Recommended Posts:



1 Average Difficulty : 1/5.0
Based on 2 vote(s)










Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.