Program to Print Fibonacci Series
Last Updated :
23 Jul, 2025
Ever wondered about the cool math behind the Fibonacci series? This simple pattern has a remarkable presence in nature, from the arrangement of leaves on plants to the spirals of seashells. We're diving into this Fibonacci Series sequence. It's not just math, it's in art, nature, and more! Let's discover the secrets of the Fibonacci series together.
What is the Fibonacci Series?
The Fibonacci series is the sequence where each number is the sum of the previous two numbers of the sequence. The first two numbers of the Fibonacci series are 0 and 1 and are used to generate the Fibonacci series.
Fibonacci SeriesHow to Find the Nth term of Fibonacci Series?
In mathematical terms, the number at the nth position can be represented by:
Fn = Fn-1 + Fn-2
where, F0 = 0 and F1 = 1.
For example, Fibonacci series 10 terms are: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34
Please refer Different Ways to Find Nth Fibonacci Number for details.
Program to print first N terms of Fibonacci Series:
Given a number n, our task is to print first n terms of the Fibonacci Series.
Input : n = 5
Output : 0 1 1 2 3
Input n = 1
Output : 0
We are simply going to run a loop and inside the loop, we are going to keep track of the previous 2 Fibonacci Numbers.
C++
// C++ Program to print the fibonacci series
// using iteration (loops)
#include <iostream>
using namespace std;
// Function to print fibonacci series
void printFib(int n)
{
if (n < 1)
{
cout << "Invalid Number of terms\n";
return;
}
// When number of terms is greater than 0
int prev1 = 1;
int prev2 = 0;
cout << prev2 << " ";
// If n is 1, then we do not need to
// proceed further
if (n == 1)
return;
cout << prev1 << " ";
// Print 3rd number onwards using
// the recursive formula
for (int i = 3; i <= n; i++)
{
int curr = prev1 + prev2;
prev2 = prev1;
prev1 = curr;
cout << curr << " ";
}
}
// Driver code
int main()
{
int n = 9;
printFib(n);
return 0;
}
C
#include <stdio.h>
// Function to print fibonacci series
void printFib(int n) {
if (n < 1) {
printf("Invalid Number of terms\n");
return;
}
// When number of terms is greater than 0
int prev1 = 1;
int prev2 = 0;
printf("%d ", prev2);
// If n is 1, then we do not need to
// proceed further
if (n == 1)
return;
printf("%d ", prev1);
// Print 3rd number onwards using
// the recursive formula
for (int i = 3; i <= n; i++) {
int curr = prev1 + prev2;
prev2 = prev1;
prev1 = curr;
printf("%d ", curr);
}
}
// Driver code
int main() {
int n = 9;
printFib(n);
return 0;
}
Java
class GfG {
// Function to print fibonacci series
static void printFib(int n) {
if (n < 1) {
System.out.println("Invalid Number of terms");
return;
}
// When number of terms is greater than 0
int prev1 = 1;
int prev2 = 0;
System.out.print(prev2 + " ");
// If n is 1, then we do not need to
// proceed further
if (n == 1)
return;
System.out.print(prev1 + " ");
// Print 3rd number onwards using
// the recursive formula
for (int i = 3; i <= n; i++) {
int curr = prev1 + prev2;
prev2 = prev1;
prev1 = curr;
System.out.print(curr + " ");
}
}
// Driver code
public static void main(String[] args) {
int n = 9;
printFib(n);
}
}
Python
# Function to print fibonacci series
def print_fib(n):
if n < 1:
print("Invalid Number of terms")
return
# When number of terms is greater than 0
prev1 = 1
prev2 = 0
print(prev2, end=" ")
# If n is 1, then we do not need to
# proceed further
if n == 1:
return
print(prev1, end=" ")
# Print 3rd number onwards using
# the recursive formula
for i in range(3, n + 1):
curr = prev1 + prev2
prev2 = prev1
prev1 = curr
print(curr, end=" ")
# Driver code
if __name__ == "__main__":
n = 9
print_fib(n)
C#
using System;
class GfG
{
// Function to print fibonacci series
static void printFib(int n)
{
if (n < 1)
{
Console.WriteLine("Invalid Number of terms");
return;
}
// When number of terms is greater than 0
int prev1 = 1;
int prev2 = 0;
Console.Write(prev2 + " ");
// If n is 1, then we do not need to
// proceed further
if (n == 1)
return;
Console.Write(prev1 + " ");
// Print 3rd number onwards using
// the recursive formula
for (int i = 3; i <= n; i++)
{
int curr = prev1 + prev2;
prev2 = prev1;
prev1 = curr;
Console.Write(curr + " ");
}
}
// Driver code
static void Main(string[] args)
{
int n = 9;
printFib(n);
}
}
JavaScript
// Function to print fibonacci series
function printFib(n) {
if (n < 1) {
console.log("Invalid Number of terms");
return;
}
// When number of terms is greater than 0
let prev1 = 1;
let prev2 = 0;
process.stdout.write(prev2 + " ");
// If n is 1, then we do not need to
// proceed further
if (n == 1) return;
process.stdout.write(prev1 + " ");
// Print 3rd number onwards using
// the recursive formula
for (let i = 3; i <= n; i++) {
let curr = prev1 + prev2;
prev2 = prev1;
prev1 = curr;
process.stdout.write(curr + " ");
}
}
// Driver code
let n = 9;
printFib(n);
Output0 1 1 2 3 5 8 13 21
Complexity Analysis
- Time Complexity: O(n)
- Auxiliary Space: O(1)
Relation Between Pascal triangle and Fibonacci numbers:
Pascal’s triangle is the arrangement of the data in triangular form which is used to represent the coefficients of the binomial expansions, i.e. the second row in Pascal’s triangle represents the coefficients in (x+y)2 and so on. In Pascal’s triangle, each number is the sum of the above two numbers. Pascal’s triangle has various applications in probability theory, combinatorics, algebra, and various other branches of mathematics.

As shown in the image the diagonal sum of the pascal's triangle forms a fibonacci sequence.
Mathematically: \Sigma_{k=0}^{\left \lfloor n/2 \right \rfloor} \binom{n-k}{k} = F_{n+1}
where F_{t}
is the t-th term of the Fibonacci sequence.
Golden Ratio:
Definition: The golden ratio, often denoted by the Greek letter phi (Φ) or the mathematical symbol τ (tau), is a special mathematical constant that has been of interest to mathematicians, scientists, artists, and architects for centuries. It is an irrational number, meaning its decimal representation goes on forever without repeating, and it is approximately equal to 1.6180339887...
The below image shows how the division of consecutive Fibonacci number forms a Golden Ratio i.e,
- x-axis : F(n+1)/F(n), where F( ) represents a Fibonacci number.
- y-axis : represents the value of the fraction obtained in x-axis.

The ratio of successive Fibonacci numbers approximates the golden ratio, and this relationship becomes more accurate as you move further along the Fibonacci sequence.
Fibonacci Spiral:
The Fibonacci spiral is created using a series of quarter circles, with radii that correspond to the Fibonacci numbers as shown in below image:
The resulting spiral is known as a "Fibonacci spiral" or a "Golden Spiral" It is often associated with the Golden Ratio, which is an irrational number approximately equal to 1.61803398875. The Fibonacci spiral is considered visually pleasing and can be found in various aspects of art, architecture, and nature due to its aesthetic qualities and mathematical significance.
Problems based on Fibonacci Number/Series:
Some Facts about Fibonacci Numbers:
- The Fibonacci numbers were first mentioned in Indian mathematics in a work by Pingala on enumerating potential patterns of Sanskrit poetry built from syllables of two lengths. The numbers were named after the Italian mathematician Leonardo of Pisa, also known as Fibonacci.
- The Fibonacci sequence and the golden ratio are often found in natural patterns, such as the arrangement of leaves on a stem, the spirals of a pinecone, the seeds in a sunflower, and in art and architecture, like the Parthenon in Athens.
- November 23 is Fibonacci Day as it forms the first 4 digits of fibonacci numbers 11/23.
- Honey bees' family tree follows fibonacci sequence.
Applications of Fibonacci Number/Series:
- Mile to kilometre approximation : If a distance in miles is a fibonacci number then the succeeding fibonacci number is its kilmometer representation. Example: If we take a number from Fibonacci series i.e., 13 then the kilometre value will be 20.9215 by formulae, which is nearly 21 by rounding.
- Financial Analysis: In the field of technical analysis in finance, Fibonacci retracement is a popular tool used to identify potential levels of support and resistance in stock and commodity price charts.
- Art and Design: The golden ratio, which is closely related to Fibonacci numbers, is often used in art and design to create aesthetically pleasing proportions and layouts. It can be seen in architecture, paintings, and sculptures.
- Data Structures and Algorithms: Fibonacci heaps, a type of data structure in computer science, are used in certain algorithms, such as Dijkstra's algorithm, for efficient graph processing.
Introduction to Fibonacci Numbers
Introduction to Fibonacci Numbers
Properties of Fibonacci Numbers
Fibonacci Divisibility and GCD
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem