Data Structures Tutorial

Data Structures Tutorial Asymptotic Notation Structure and Union Array Data Structure Linked list Data Structure Type of Linked list Advantages and Disadvantages of linked list Queue Data Structure Implementation of Queue Stack Data Structure Implementation of Stack Sorting Insertion sort Quick sort Selection sort Heap sort Merge sort Bucket sort Count sort Radix sort Shell sort Tree Traversal of the binary tree Binary search tree Graph Spanning tree Linear Search Binary Search Hashing Collision Resolution Techniques

Misc Topic:

Priority Queue in Data Structure Deque in Data Structure Difference Between Linear And Non Linear Data Structures Queue Operations In Data Structure About Data Structures Data Structures Algorithms Types of Data Structures Big O Notations Introduction to Arrays Introduction to 1D-Arrays Operations on 1D-Arrays Introduction to 2D-Arrays Operations on 2D-Arrays Strings in Data Structures String Operations Application of 2D array Bubble Sort Insertion Sort Sorting Algorithms What is DFS Algorithm What Is Graph Data Structure What is the difference between Tree and Graph What is the difference between DFS and BFS Bucket Sort Dijkstra’s vs Bellman-Ford Algorithm Linear Queue Data Structure in C Stack Using Array Stack Using Linked List Recursion in Fibonacci Stack vs Array What is Skewed Binary Tree Primitive Data Structure in C Dynamic memory allocation of structure in C Application of Stack in Data Structures Binary Tree in Data Structures Heap Data Structure Recursion - Factorial and Fibonacci What is B tree what is B+ tree Huffman tree in Data Structures Insertion Sort vs Bubble Sort Adding one to the number represented an array of digits Bitwise Operators and their Important Tricks Blowfish algorithm Bubble Sort vs Selection Sort Hashing and its Applications Heap Sort vs Merge Sort Insertion Sort vs Selection Sort Merge Conflicts and ways to handle them Difference between Stack and Queue AVL tree in data structure c++ Bubble sort algorithm using Javascript Buffer overflow attack with examples Find out the area between two concentric circles Lowest common ancestor in a binary search tree Number of visible boxes putting one inside another Program to calculate the area of the circumcircle of an equilateral triangle Red-black Tree in Data Structures Strictly binary tree in Data Structures 2-3 Trees and Basic Operations on them Asynchronous advantage actor-critic (A3C) Algorithm Bubble Sort vs Heap Sort Digital Search Tree in Data Structures Minimum Spanning Tree Permutation Sort or Bogo Sort Quick Sort vs Merge Sort Boruvkas algorithm Bubble Sort vs Quick Sort Common Operations on various Data Structures Detect and Remove Loop in a Linked List How to Start Learning DSA Print kth least significant bit number Why is Binary Heap Preferred over BST for Priority Queue Bin Packing Problem Binary Tree Inorder Traversal Burning binary tree Equal Sum What is a Threaded Binary Tree? What is a full Binary Tree? Bubble Sort vs Merge Sort B+ Tree Program in Q language Deletion Operation from A B Tree Deletion Operation of the binary search tree in C++ language Does Overloading Work with Inheritance Balanced Binary Tree Binary tree deletion Binary tree insertion Cocktail Sort Comb Sort FIFO approach Operations of B Tree in C++ Language Recaman’s Sequence Tim Sort Understanding Data Processing Applications of trees in data structures Binary Tree Implementation Using Arrays Convert a Binary Tree into a Binary Search Tree Create a binary search tree Horizontal and Vertical Scaling Invert binary tree LCA of binary tree Linked List Representation of Binary Tree Optimal binary search tree in DSA Serialize and Deserialize a Binary Tree Tree terminology in Data structures Vertical Order Traversal of Binary Tree What is a Height-Balanced Tree in Data Structure Convert binary tree to a doubly linked list Fundamental of Algorithms Introduction and Implementation of Bloom Filter Optimal binary search tree using dynamic programming Right side view of binary tree Symmetric binary tree Trim a binary search tree What is a Sparse Matrix in Data Structure What is a Tree in Terms of a Graph What is the Use of Segment Trees in Data Structure What Should We Learn First Trees or Graphs in Data Structures All About Minimum Cost Spanning Trees in Data Structure Convert Binary Tree into a Threaded Binary Tree Difference between Structured and Object-Oriented Analysis FLEX (Fast Lexical Analyzer Generator) Object-Oriented Analysis and Design Sum of Nodes in a Binary Tree What are the types of Trees in Data Structure What is a 2-3 Tree in Data Structure What is a Spanning Tree in Data Structure What is an AVL Tree in Data Structure Given a Binary Tree, Check if it's balanced B Tree in Data Structure Convert Sorted List to Binary Search Tree Flattening a Linked List Given a Perfect Binary Tree, Reverse Alternate Levels Left View of Binary Tree What are Forest Trees in Data Structure Compare Balanced Binary Tree and Complete Binary Tree Diameter of a Binary Tree Given a Binary Tree Check the Zig Zag Traversal Given a Binary Tree Print the Shortest Path Given a Binary Tree Return All Root To Leaf Paths Given a Binary Tree Swap Nodes at K Height Given a Binary Tree Find Its Minimum Depth Given a Binary Tree Print the Pre Order Traversal in Recursive Given a Generate all Structurally Unique Binary Search Trees Perfect Binary Tree Threaded Binary Trees Function to Create a Copy of Binary Search Tree Function to Delete a Leaf Node from a Binary Tree Function to Insert a Node in a Binary Search Tree Given Two Binary Trees, Check if it is Symmetric A Full Binary Tree with n Nodes Applications of Different Linked Lists in Data Structure B+ Tree in Data Structure Construction of B tree in Data Structure Difference between B-tree and Binary Tree Finding Rank in a Binary Search Tree Finding the Maximum Element in a Binary Tree Finding the Minimum and Maximum Value of a Binary Tree Finding the Sum of All Paths in a Binary Tree Time Complexity of Selection Sort in Data Structure How to get Better in Data Structures and Algorithms Binary Tree Leaf Nodes Classification of Data Structure Difference between Static and Dynamic Data Structure Find the Union and Intersection of the Binary Search Tree Find the Vertical Next in a Binary Tree Finding a Deadlock in a Binary Search Tree Finding all Node of k Distance in a Binary Tree Finding Diagonal Sum in a Binary Tree Finding Diagonal Traversal of The Binary Tree Finding In-Order Successor Binary Tree Finding the gcd of Each Sibling of the Binary Tree Greedy Algorithm in Data Structure How to Calculate Space Complexity in Data Structure How to find missing numbers in an Array Kth Ancestor Node of Binary Tree Minimum Depth Binary Tree Mirror Binary Tree in Data Structure Red-Black Tree Insertion Binary Tree to Mirror Image in Data Structure Calculating the Height of a Binary Search Tree in Data Structure Characteristics of Binary Tree in Data Structure Create a Complete Binary Tree from its Linked List Field in Tree Data Structure Find a Specified Element in a binary Search Tree Find Descendant in Tree Data Structure Find Siblings in a Binary Tree Given as an Array Find the Height of a Node in a Binary Tree Find the Second-Largest Element in a Binary Tree Find the Successor Predecessor of a Binary Search Tree Forest of a Tree in Data Structure In Order Traversal of Threaded Binary Tree Introduction to Huffman Coding Limitations of a Binary Search Tree Link State Routing Algorithm in Data Structure Map Reduce Algorithm for Binary Search Tree in Data Structure Non-Binary Tree in Data Structure Quadratic Probing Example in Hashing Scope and Lifetime of Variables in Data Structure Separate Chaining in Data Structure What is Dynamic Data Structure Separate Chaining vs Open Addressing Time and Space Complexity of Linear Data Structures Abstract Data Types in Data Structures Binary Tree to Single Linked List Count the Number of Nodes in the Binary Tree Count Total No. of Ancestors in a Binary Search Tree Elements of Dynamic Programming in Data Structures Find cost of tree with prims algorithm in data structures Find Preorder Successor in a Threaded Binary Tree Find Prime Nodes Sum Count in Non-Binary Tree Find the Right Sibling of a Binary Tree with Parent Pointers Find the Width of the Binary Search Tree Forest trees in Data Structures Free Tree in Data Structures Frequently asked questions in Tree Data Structures Infix, Postfix and Prefix Conversion Time Complexity of Fibonacci Series What is Weighted Graph in Data Structure What is the Advantage of Linear Search?

Recursion - Factorial and Fibonacci

In this article, we will learn how to find the factorial of a number and the Fibonacci series up to n using the recursion method.

What is recursion?

Defining anything in terms of itself is called recursion. Recursion is so powerful tool in the programming language that we used to solve many real-life problems easily. When in the body of a function, if any statement calls the same function or another function then that function is recursive in nature. The properties of recursion include the base criteria and progressive approach. Any recursive function should follow these two essential properties.

The Base criteria or conditions define the condition for the function call to stop, and the progressive approach defines that the result should come close to the base criteria after each function call.

  • Factorial – The factorial of a number is defined as the product of all the integers less than it and the number itself. It is determined as n! = n * (n-1)!

Q. Write a C++ program to print the factorial of a number using the recursive method.

// C++ program to find the factorial of a number using recursive method.
#include <iostream>
using namespace std;


// Function to calculate the factorial of a number through recursion.
int factorial(int n)
{
    // Base Criteria
    if (n == 0 || n == 1)
    {
        return 1;
    }


    // Calculating the factorial using the recursive method.
    else
    {
        return n * factorial(n - 1);
    }
}


// Driver Function
int main()
{
    // Variable to store the user inputs
    int x;
    cout << "To exit the program enter a negative number!" << endl;
    while (1) // Always True
    {
        cout << "Enter a number: ";
        cin >> x;


        // The while loop terminates when the user enters a negative integer.
        if (x < 0)
        {
            cout << "Exited Successfully!" << endl;
            break;
        }
        // Calling the factorial function, passing the value, and storing it in the fact variable.
        int fact = factorial(x);


        // Ternary operator
        fact > 0 ? cout << "The factorial of " << x << " is = " << fact << endl : cout << "Enter a positive number!" << endl;
    }


    return 0;
}

The possible output of the above program is given below:

Enter a negative number to exit the program!
Enter a number: 0
The factorial of 0 is = 1
Enter a number: 4
The factorial of 4 is = 24
Enter a number: 5
The factorial of 5 is = 120
Enter a number: 10
The factorial of 10 is = 3628800
Enter a number: -1
Exited Successfully!

As we know, the factorial of zero and one is 1. Hence, in the base criteria of the factorial function, we return 1 if the value of n is 0 or 1. In the else part, we return the product of factorial (n-1) and n itself.

int factorial(int n)
{
    if (n == 0 || n == 1)
    {
        return 1;
    }
    else
    {
        return n * factorial(n - 1);
    }
}

Let us now see the activation record after each function calls and how these recursive functions calls are done:

OperationActivation RecordValue ReturnRemark
Push(main())main()-The main function is called, and we enter n = 5. The main function is pushed into the stack as soon as it calls the factorial function. The control is transferred to the factorial function.
Push(factorial(5))factorial(5) main()-Here, n = 5; hence the base condition is not satisfied, and in the else, it calls itself with n = 4. It is pushed into the stack, and the control is transferred to the factorial function with n = 4.
Push(factorial(4))factorial(4) factorial(5) main()-Here also, the base condition is not satisfied. We push Factorial (4) because it calls itself with the value of n = 3.
Push(factorial(3))factorial(3) factorial(4) factorial(5) main()-We push Factorial (3) because it calls itself with the value of n = 2.
Push(factorial(2))factorial(2) factorial(3) factorial(4) factorial(5) main()Factorial (1) = 1We push Factorial (2) because it also calls itself with the value n = 1. Here, the base condition is satisfied, and factorial (1) returns 1.
Pop(factorial(2))factorial(3) factorial(4) factorial(5) main()Factorial (2) = 2Factorial (2) returns 2 and is popped from the stack. The control is again transferred to factorial(3).
Pop(factorial(3))factorial(4) factorial(5) main()Factorial (3) = 6Factorial (3) returns 6 and is popped from the stack. The control is now transferred to factorial(4).
Pop(factorial(4))factorial(5) main()Factorial (4) = 24Factorial (4) returns 24 and is popped from the stack. The control is now transferred to factorial(5).
Pop(factorial(3))main()Factorial (5) = 120Factorial (5) returns 120 and is popped from the stack. The control is again transferred to the main function.
Pop(main())NULL0The program terminates after the main function returns 0.

The above function calls are shown in the figure below and the numbering associated with them tells us which function call is evaluated first:

Recursion – Factorial and Fibonacci
  • Fibonacci Series – In the Fibonacci series, the nth term is equal to the sum of the previous two terms of the series.

Q. Write a C++ program to print the Fibonacci series up to n terms.

// C++ program to print the Fibonacci series up to n terms.
#include <iostream>
using namespace std;


// Function to find any term of the Fibonacci series.
int fibonacci_series(int n)
{
    // Base Criteria
    if (n == 0 || n == 1)
    {
        return n;
    }


    // Recursive Method
    else
    {
        return fibonacci_series(n - 1) + fibonacci_series(n - 2);
    }
}


// Driver Function
int main()
{
    int n, x;
    cout << "Enter a number: ";
    cin >> n;
    cout << "Fibonacci Series up to n terms: ";


    // Calling the function n times.
    for (int i = 0; i < n; i++)
    {
        x = fibonacci_series(i);
        cout << x << " ";
    }
    return 0;
}

The sample output of the above program is given below:

// Output 1
Enter a number: 5
Fibonacci Series up to n terms: 0 1 1 2 3


// Output 2
Enter a number: 10
Fibonacci Series up to n terms: 0 1 1 2 3 5 8 13 21 34


// Output 3
Enter a number: 15
Fibonacci Series up to n terms: 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377

In the above method, we have used recursion to find the Fibonacci series. Let us see how the function calls are done in the above method. Assume that n = 5 is passed to the fibonacci_series function. We have used fib for the Fibonacci function.

OperationActivation RecordValue ReturnRemark
Push(main())main()-The main function calls the Fibonacci function with n = 5. Hence, it is pushed into the stack, and the control is transferred to the Fibonacci function.
Push(fib(5))fib(5) main()-The fib(5) function calls the fib(4) and fib(3) functions. So, we pushed it into the stack. Here, we have two function calls, fib(4) will be evaluated first and then fib(3).
Push(fib(3))fib(3) fib(5) main()-Fib(4) is called itself, so we push fib(3) into the stack and start evaluating fib(4).
Push(fib(4))fib(4) fib(3) fib(5) main()-The fib(4) calls fib(3) and fib(2). So we push fib(4) into the stack.
Push(fib(2)fib(2) fib(4) fib(3) fib(5) main()-Fib(3) is called itself, so we push fib(2) into the stack and start evaluating fib(3).
Push(fib(3))fib(3) fib(2) fib(4) fib(3) fib(5) main()-But fib(3) calls fib(2) and fib(1), so we push fib(3) in the stack. Now, we evaluate fib(2) first and then fib(1).
Push(fib(1))  fib(1) fib(3) fib(2) fib(4) fib(3) fib(5) main()-Fib(2) is called itself. So, we push fib(1) into the stack and start evaluating fib(2).
Push(fib(2))fib(2) fib(1) fib(3) fib(2) fib(4) fib(3) fib(5) main()-But fib(2) calls fib(1) and fib(0), so we push fib(2) in the stack.
Push(fib(0))fib(0) fib(2) fib(1) fib(3) fib(2) fib(4) fib(3) fib(5) main()Fib(1) = 1Now, fib(1) will be called itself and we push fib(0) into the stack. Fib(1) returns 1 to its previous call, which is fib(2).
Pop()fib(2) fib(1) fib(3) fib(2) fib(4) fib(3) fib(5) main()fib(0) = 0We pop fib(0) from the stack, which returns 0 to fib(2). Now, evaluate fib(2).
Pop()fib(1) fib(3) fib(2) fib(4) fib(3) fib(5) main()fib(2) = 1We pop fib(2) from the stack. Fib(2) returns 1 sum of fib(1) = 1 and fib(0) = 0 to fib(3). Now, evaluate fib(1).
Pop()fib(3) fib(2) fib(4) fib(3) fib(5) main()fib(1) = 1We pop fib(1) from the stack, which returns 1 to fib(3). Now, evaluate fib(3).
Pop()fib(2) fib(4) fib(3) fib(5) main()fib(3) = 2We pop fib(3) from the stack which returns 2 sum of fib(2) = 1 and fib(1) = 1 to fib(4). Now evaluate fib(2).
Push(fib(0))fib(0) fib(2) fib(4) fib(3) fib(5) main()fib(1) = 1Here, fib(2) calls fib(1) and fib(0). Fib(1) is called itself and we push fib(0) into the stack. On evaluating fib(1) returns 1 to fib(2).
Pop()fib(2) fib(4) fib(3) fib(5) main()fib(0) = 0We pop fib(0) from the stack, which returns 0 to fib(2). Now, evaluate fib(2).
Pop()fib(4) fib(3) fib(5) main()fib(2) = 1We pop fib(2) from the stack which returns 1 sum of fib(1) = 1 and fib(0) = 0 to fib(4). Now, evaluate fib(4).
Pop()fib(3) fib(5) main()fib(4) = 3We pop fib(4) from the stack which returns 3 sum of fib(3) = 2 and fib(2) = 1 to fib(4). Now, evaluate fib(3).
Push(fib(1))  fib(1) fib(3) fib(5) main()-Here, fib(3) calls fib(2) and fib(1). Fib(2) is called itself, so we push fib(1) into the stack.
Push(fib(2))fib(2) fib(1) fib(3) fib(5) main() Here, fib(2) calls fib(1) and fib(0). So we push fib(2) in the stack.
Push(fib(0))fib(0) fib(2) fib(1) fib(3) fib(5) main()fib(1) = 1Fib(1) is called itself, so we push fib(0) in the stack. Here, fib(1)  returns 1 to fib(2) as per the base condition. Now, evaluate fib(0).
Pop()fib(2) fib(1) fib(3) fib(5) main()fib(0) = 0We pop fib(0) from the stack, which returns 0 to fib(2) as per the base condition. Now evaluate fib(2).
Pop()fib(1) fib(3) fib(5) main()fib(2) = 1We pop fib(2) from the stack. Fib(2) returns 1 sum of fib(1) = 1 and fib(0) = 0 to fib(3). Now, evaluate fib(1).
pop()fib(3) fib(5) main()fib(1) = 1We pop fib(1) from the stack, which returns 1 to fib(3). Now, evaluate fib(3).
Pop()fib(5) main()fib(3) = 3We pop fib(3) from the stack which returns 2 sum of fib(2) = 1 and fib(1) = 1 to fib(5). Now evaluate fib(5).
Pop()    main()fib(5) = 5We pop fib(5) from the stack which returns 5 sum of fib(4) = 3 and fib(3) = 2 to the main function. The control now transfers to the main function
Pop()Empty stack-The main function runs other lines of code, and then the program terminates.

The above function call is also shown in the figure given below, and the numbering associative with each function calls tell us which function call is evaluated first. 

Recursion – Factorial and Fibonacci