Program to print first 10 numbers of Fibonacci series
Last Updated :
21 Feb, 2024
Find the first 10 numbers of Fibonacci series.
The Fibonacci sequence is a sequence where the next term is the sum of the previous two terms. The first two terms of the Fibonacci sequence are 0 followed by 1.
The Fibonacci sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21, ……..
Approach: To solve the problem, follow the below idea:
We can take two variables f1 and f2 to store the first and second term. In order to calculate the next terms, we can take the sum of previous two terms f1 and f2 and then update f1 with f2 and f2 with the new term. Repeat for 10 times to get first 10 numbers of Fibonacci Sequence.
Step-by-step algorithm:
- Use two variables f1 and f2 and initialize with 0 and 1 respectively because the 1st and 2nd elements of the Fibonacci series are 0 and 1 respectively.
- Iterate from 1 to 9 as we have to print first 10 numbers and print f2 then store f2 in temp variable and update f2 with f2 + f1 and f1 as f2.
Below is the implementation of the approach:
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(10);
return 0;
}
|
Java
public class Fibonacci {
static void printFibonacciNumbers( int n) {
int f1 = 0 , f2 = 1 ;
if (n < 1 )
return ;
System.out.print(f1 + " " );
for ( int i = 1 ; i < n; i++) {
System.out.print(f2 + " " );
int next = f1 + f2;
f1 = f2;
f2 = next;
}
}
public static void main(String[] args) {
printFibonacciNumbers( 10 );
}
}
|
Python3
def print_fibonacci_numbers(n):
f1, f2 = 0 , 1
if n < 1 :
return
print (f1, end = " " )
for i in range ( 1 , n):
print (f2, end = " " )
next_fibonacci = f1 + f2
f1, f2 = f2, next_fibonacci
if __name__ = = "__main__" :
print_fibonacci_numbers( 10 )
|
C#
using System;
class Program
{
static void PrintFibonacciNumbers( int n)
{
int f1 = 0, f2 = 1;
if (n < 1)
return ;
Console.Write(f1 + " " );
for ( int i = 1; i < n; i++)
{
Console.Write(f2 + " " );
int next = f1 + f2;
f1 = f2;
f2 = next;
}
}
static void Main()
{
PrintFibonacciNumbers(10);
Console.ReadLine();
}
}
|
Javascript
function print_fibonacci_numbers(n) {
let f1 = 0, f2 = 1;
if (n < 1) {
return ;
}
console.log(f1);
for (let i = 1; i < n; i++) {
console.log(f2);
const next_fibonacci = f1 + f2;
f1 = f2;
f2 = next_fibonacci;
}
}
print_fibonacci_numbers(10);
|
Output
0 1 1 2 3 5 8 13 21 34
Time Complexity: O(10) ~ O(1)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...