Following is a simple program to print first n Fibonacci numbers.

Examples :
Input : n = 3
Output : 0 1 1
Input : n = 7
Output : 0 1 1 2 3 5 8
C++
#include <bits/stdc++.h>
using namespace std;
void printFibonacciNumbers(int n)
{
int f1 = 0, f2 = 1, i;
if (n < 1)
return;
cout << f1 << " ";
for (i = 1; i < n; i++) {
cout << f2 << " ";
int next = f1 + f2;
f1 = f2;
f2 = next;
}
}
int main()
{
printFibonacciNumbers(7);
return 0;
}
|
C
#include <stdio.h>
void printFibonacciNumbers(int n)
{
int f1 = 0, f2 = 1, i;
if (n < 1)
return;
printf("%d ", f1);
for (i = 1; i < n; i++) {
printf("%d ", f2);
int next = f1 + f2;
f1 = f2;
f2 = next;
}
}
int main()
{
printFibonacciNumbers(7);
return 0;
}
|
Java
class Test {
static void printFibonacciNumbers(int n)
{
int f1 = 0, f2 = 1, i;
if (n < 1)
return;
System.out.print(f1 + " ");
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);
}
}
|
Python3
def printFibonacciNumbers(n):
f1 = 0
f2 = 1
if (n < 1):
return
print(f1, end=" ")
for x in range(1, n):
print(f2, end=" ")
next = f1 + f2
f1 = f2
f2 = next
printFibonacciNumbers(7)
|
C#
using System;
class Test {
static void printFibonacciNumbers(int n)
{
int f1 = 0, f2 = 1, i;
if (n < 1)
return;
Console.Write(f1 + " ");
for (i = 1; i < n; i++) {
Console.Write(f2 + " ");
int next = f1 + f2;
f1 = f2;
f2 = next;
}
}
public static void Main()
{
printFibonacciNumbers(7);
}
}
|
PHP
<?php
function printFibonacciNumbers($n)
{
$f1 = 0;
$f2 = 1;
$i;
if ($n < 1)
return;
echo($f1);
echo(" ");
for ($i = 1; $i < $n; $i++)
{
echo($f2);
echo(" ");
$next = $f1 + $f2;
$f1 = $f2;
$f2 = $next;
}
}
printFibonacciNumbers(7);
?>
|
Javascript
<script>
function printFibonacciNumbers(n)
{
let f1 = 0, f2 = 1, i;
if (n < 1)
return;
document.write(f1 + " ");
for (i = 1; i < n; i++) {
document.write(f2 + " ");
let next = f1 + f2;
f1 = f2;
f2 = next;
}
}
printFibonacciNumbers(7);
</script>
|
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.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.