C Program to print first n Fibonacci Numbers

Following is simple program to print first n Fibonacci numbers.

C

#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 4 5 6

GATE CS Corner    Company Wise Coding Practice

Recommended Posts:







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