The Wayback Machine - https://web.archive.org/web/20240717181821/https://www.geeksforgeeks.org/finite-and-infinite-recursion-with-examples/
Open In App

Finite and Infinite Recursion with examples

Last Updated : 27 Jan, 2023
Improve
Suggest changes
Post a comment
Like Article
Like
Save
Share
Report

The process in which a function calls itself directly or indirectly is called Recursion and the corresponding function is called a Recursive function. 
Using Recursion, certain problems can be solved quite easily. Examples of such problems are Towers of Hanoi (TOH), Inorder/Preorder/Postorder Tree Traversals, DFS, etc.

Types of Recursions:

Recursion can be further classified into two kinds, depending on when they terminate:

  1. Finite Recursion
  2. Infinite Recursion

Finite Recursion:

Finite Recursion occurs when the recursion terminates after a finite number of recursive calls. A recursion terminates only when a base condition is met.

Example:

Below is an implementation to demonstrate Finite Recursion.

C++




// C++ program to demsonstrate Finite Recursion
#include <bits/stdc++.h>
using namespace std;
 
// Recursive function
void Geek(int N)
{
    // Base condition
    // When this condition is met,
    // the recursion terminates
    if (N == 0)
        return;
 
    // Print the current value of N
    cout << N << " ";
 
    // Call itself recursively
    Geek(N - 1);
}
 
// Driver code
int main()
{
 
    // Initial value of N
    int N = 5;
 
    // Call the recursive function
    Geek(N);
    return 0;
}


Java




// Java program for the above approach
class GFG{
 
// Recursive function
static void Geek(int N)
{
     
    // Base condition
    // When this condition is met,
    // the recursion terminates
    if (N == 0)
        return;
 
    // Print the current value of N
    System.out.println(N + " ");
 
    // Call itself recursively
    Geek(N - 1);
}
 
// Driver code
public static void main(String[] args)
{
     
    // Initial value of N
    int N = 5;
 
    // Call the recursive function
    Geek(N);
}
}
 
// This code is contributed by abhinavjain194


Python3




# Python program to demsonstrate Finite Recursion
# Recursive function
def Geek( N):
 
    # Base condition
    # When this condition is met,
    # the recursion terminates
    if (N == 0):
        return
 
    # Pr the current value of N
    print( N, end =" " )
 
    # Call itself recursively
    Geek(N - 1)
 
 
# Driver code
# Initial value of N
N = 5
 
# Call the recursive function
Geek(N)
 
# this code is contributed by shivanisinghss2110


C#




// C# program for the above approach
using System;
using System.Collections.Generic;
 
class GFG{
 
// Recursive function
static void Geek(int N)
{
      
    // Base condition
    // When this condition is met,
    // the recursion terminates
    if (N == 0)
        return;
  
    // Print the current value of N
    Console.Write(N + " ");
  
    // Call itself recursively
    Geek(N - 1);
}
 
// Driver Code
public static void Main(String[] args)
{
   
    // Initial value of N
    int N = 5;
  
    // Call the recursive function
    Geek(N);
}
}
 
// This code is contributed by target_2.


Javascript




<script>
 
// JavaScript program to demsonstrate Finite Recursion
// Recursive function
function Geek(N)
{
    // Base condition
    // When this condition is met,
    // the recursion terminates
    if (N == 0)
        return;
 
    // Print the current value of N
    document.write(N +" ");
 
    // Call itself recursively
    Geek(N - 1);
}
 
// Driver code
// Initial value of N
    var N = 5;
 
    // Call the recursive function
    Geek(N);
     
 // this code is contributed by shivanisinghss2110
  
</script>


Output

5 4 3 2 1 

Time Complexity: O(n)
Auxiliary Space: O(n)

The recursion tree for the above recursive function looks like this.

Recursion Tree

When the value of N becomes 0, because of the base condition, the recursion terminates.

Infinite Recursion:

Infinite Recursion occurs when the recursion does not terminate after a finite number of recursive calls. As the base condition is never met, the recursion carries on infinitely.

Example: 

Below is an implementation to demonstrate Infinite Recursion. 

C++




// C++ program to demsonstrate Infinite Recursion
#include <bits/stdc++.h>
using namespace std;
 
// Recursive function
void Geek(int N)
{
    // Base condition
    // This condition is never met here
    if (N == 0)
        return;
 
    // Print the current value of N
    cout << N << " ";
 
    // Call itself recursively
    Geek(N);
}
 
// Driver code
int main()
{
 
    // Initial value of N
    int N = 5;
 
    // Call the recursive function
    Geek(N);
    return 0;
}


Java




// Java program to demsonstrate Infinite Recursion
import java.io.*;
  
class GFG
{
// Recursive function
static void Geek(int N)
{
    // Base condition
    // This condition is never met here
    if (N == 0)
        return;
 
    // Print the current value of N
    System.out.print( N +" ");
 
    // Call itself recursively
    Geek(N);
}
 
// Driver code
public static void main(String[] args)
    {
 
    // Initial value of N
    int N = 5;
 
    // Call the recursive function
    Geek(N);
    }
}
 
// This code is contributed by shivanisinghss2110


Python3




# Python3 to demsonstrate Infinite Recursion
 
# Recursive function
def Geek(N):
     
    # Base condition
    # This condition is never met here
    if (N == 0):
        return
 
    # Print the current value of N
    print(N, end = " " )
 
    # Call itself recursively
    Geek(N)
 
# Driver code
 
# Initial value of N
N = 5
 
# Call the recursive function
Geek(N)
 
# This code is contributed by shivanisinghss2110


C#




// C# program to demsonstrate Infinite Recursion
using System;
  
class GFG
{
// Recursive function
static void Geek(int N)
{
    // Base condition
    // This condition is never met here
    if (N == 0)
        return;
 
    // Print the current value of N
    Console.Write( N +" ");
 
    // Call itself recursively
    Geek(N);
}
 
// Driver code
public static void Main(String[] args)
    {
 
    // Initial value of N
    int N = 5;
 
    // Call the recursive function
    Geek(N);
    }
}
 
// This code is contributed by shivanisinghss2110


Javascript




<script>
// JavaScript program to demsonstrate Infinite Recursion
// Recursive function
function Geek(N)
{
    // Base condition
    // This condition is never met here
    if (N == 0)
        return;
 
    // Print the current value of N
    document.write( N +" ");
 
    // Call itself recursively
    Geek(N);
}
 
// Driver code
    // Initial value of N
    var N = 5;
 
    // Call the recursive function
    Geek(N);
 
// This code is contributed by shivanisinghss2110
</script>


Time Complexity: non finite as this recursion will never end.
Auxiliary Space: non finite

The recursion tree for the above recursive function looks like this.

Recursion Tree

Since the value of N never becomes 0, so the recursion never terminates. Instead, the recursion continues until the implicit stack becomes full which results in a Stack Overflow. Some compilers directly give the output as Segmentation Fault (Core Dumped), while others may abnormally terminate for some value and then show Segmentation fault. 



Previous Article
Next Article

Similar Reads

Find Nth item distributed from infinite items of infinite types based on given conditions
Given a positive integer N, the task is to find the Nth item given out when there are infinite items of the infinite number of types such that the items are given out in the following fashion: Day 1: 1 item of Type-I are given out.Day 2: 2 items of the Type-II and 1 item of Type-I are given out.Day 3: 3 items of the Type-III, 2 items of the Type-II
10 min read
Why is Tail Recursion optimization faster than normal Recursion?
What is tail recursion? Tail recursion is defined as a recursive function in which the recursive call is the last statement that is executed by the function. So basically nothing is left to execute after the recursion call. What is non-tail recursion? Non-tail or head recursion is defined as a recursive function in which the recursive call is the f
4 min read
Measure one litre using two vessels and infinite water supply
There are two vessels of capacities 'a' and 'b' respectively. We have infinite water supply. Give an efficient algorithm to make exactly 1 litre of water in one of the vessels. You can throw all the water from any vessel any point of time. Assume that 'a' and 'b' are Coprimes.Following are the steps: Let V1 be the vessel of capacity 'a' and V2 be t
15 min read
Find the index of first 1 in an infinite sorted array of 0s and 1s
Given an infinite sorted array consisting 0s and 1s. The problem is to find the index of first ‘1’ in that array. As the array is infinite, therefore it is guaranteed that number '1' will be present in the array. Examples: Input : arr[] = {0, 0, 1, 1, 1, 1} Output : 2 Input : arr[] = {1, 1, 1, 1,, 1, 1} Output : 0 Approach: The problem is closely r
9 min read
Best Time to Buy and Sell Stock II (infinite transactions allowed)
Given an array prices[] of size N denoting the cost of stock on each day, the task is to find the maximum total profit if we can buy and sell the stocks any number of times. Note: We can only sell a stock which we have bought earlier and we cannot hold multiple stocks on any day. Examples: Input: prices[] = {100, 180, 260, 310, 40, 535, 695}Output:
15 min read
Number of possible Equivalence Relations on a finite set
An equivalence relation is Reflexive, Symmetric and Transitive. Before counting the number of possible equivalence relations on a set |A|=n, let us see an example of a equivalence relation and identify Equivalence Classes in it. Let A = {1, 2, 3, 4} be a set and R = {(1, 1), (1, 2), (2, 1), (2, 2), (3, 3), (3, 4), (4, 3), (4, 4)} be an equivalence
4 min read
Find initial integral solution of Linear Diophantine equation if finite solution exists
Given three integers a, b, and c representing a linear equation of the form: ax + by = c. The task is to find the initial integral solution of the given equation if a finite solution exists. A Linear Diophantine equation (LDE) is an equation with 2 or more integer unknowns and the integer unknowns are each to at most degree of 1. Linear Diophantine
8 min read
Finite Automata algorithm for Pattern Searching
Given a text txt[0..n-1] and a pattern pat[0..m-1], write a function search(char pat[], char txt[]) that prints all occurrences of pat[] in txt[]. You may assume that n &gt; m.Examples: Input: txt[] = "THIS IS A TEST TEXT" pat[] = "TEST" Output: Pattern found at index 10 Input: txt[] = "AABAACAADAABAABA" pat[] = "AABA" Output: Pattern found at inde
13 min read
Pattern Searching | Set 6 (Efficient Construction of Finite Automata)
In the previous post, we discussed the Finite Automata-based pattern searching algorithm. The FA (Finite Automata) construction method discussed in the previous post takes O((m^3)*NO_OF_CHARS) time. FA can be constructed in O(m*NO_OF_CHARS) time. In this post, we will discuss the O(m*NO_OF_CHARS) algorithm for FA construction. The idea is similar t
9 min read
C program to simulate Nondeterministic Finite Automata (NFA)
Background An NFA is typically described using a directed graph. Each edge and vertex is labeled either 0 or 1 representing possible transitions. Vertices represent the states of the NFA. Those labeled 0 are non­ accepting states, and those labeled 1 are accepting states. It takes an input string of finite length. Typically, the input string is a b
6 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg