×

Dart Recursion

Recursion is one of the most important and interesting concepts in any programming language. It can be defined as a process in which a function calls itself directly or indirectly. It is used to solve large complex problems by breaking them into smaller subproblems.

Recursion can be of two types :

  1. Direct Recursion – In this type of recursion, a function calls itself from within itself.
  2. Indirect Recursion – In this type of recursion, a function calls another function and vice - versa.

In recursion, the recursive function calls itself repeatedly until a base condition is reached and stops calling when it evaluates to false. The function basically has two parts.

Recursive: The recursive part of the function is called again and again with a smaller subproblem.

Base: The base condition is a Boolean condition which is checked every time a function call is made. If the function is in a base condition it is used to provide a solution.

A function can be made recursive only if:

  1. The function can be defined in terms of itself.
  2. The function must have a definite terminating condition.
  3. Every recursive call to the function must take it closer to the terminating condition.

Recursion uses Recursion stack to store the resultant value of the subproblems to be later returned to the main problem. Execution of the call statement every time results in some outcome value that is pushed in stack. When the base condition is reached, back-tracking begins and all the numbers are popped out of the stack.

Syntax:

void func_name( )
{
    // Base code . . . .
    func_name( ) ;
    // Some code...
}
void main( )
{
    func_name( ) ;
}

Consider the following code in Dart that prints the factorial of the number using the concept of recursion.

Program

import 'dart:io';
int recur( int n ) {
  int fact = 1 ;
  if ( n == 1 )
    return 1 ;
  else
    fact = n * recur( n – 1 ) ;
  return fact ;
}
int main( ) {
  print( ' Enter the number of which you want to find the factorial :  ' ) ;
  int? n = int.parse( stdin.readLineSync( ) ! ) ;
  int fact = recur( n ) ;
  print( ' \n Factorial of the number is : $fact ' ) ;
  return 0 ;
}

Output :

Enter the number of which you want to find the factorial :
5


Factorial of the number is : 120

Explanation :

Consider the above code in Dart that prints the factorial of the number 5 which is 120. The function recur (int n) accepts one argument n of integer type and return type of integer which signifies that the function returns an integer value.

If the value of n is 1, then simply return 1 because the factorial of 1 is 1 only. Else if n is any number other than 1 the function recursively calls itself and stores the temporary product in ‘fact’ variable. This recursive call is made till n is 1.

The computation takes place as follows :

First call :       when n = 5

                        fact = 5 * recur( 4 )

                        5 goes in recursion stack.

recur( int n ) function is called again.

Second call :   n = 4

                        fact = 4 * recur ( 3 )

                        4 goes in recursion stack.

recur( int n ) function is called again.

Third call :     n = 3

                        fact = 3 * recur ( 2 )

                        3 goes in recursion stack.

recur( int n ) function is called again.

Fourth call :   n = 2

                        fact = 2 * recur( 1 )

                        2 goes in recursion stack.

Since in the next call, n becomes 1, 1 is returned.

In the case of Recursion, the recursive call every time should take it closer to the terminating condition as the problem has to be terminated to return a final result.  If the base condition is not set properly or the function isn't defined in its term properly, the problem does not terminate. This leads to an infinite loop.

As explained earlier these function calls use stack memory to store the temporary values. This definitely takes up a lot of memory. The function can cause stack overflow if the base condition is not defined or unable to reach. This condition is called as Terminating condition in Recursion.

Advantages of using Recursion:

  • The solution of the problem using recursive function is concise and easy.
  • Recursive functions are prominently used with the problems related to data structures such as trees and graphs.
  • Recursion reduces the time complexity of the algorithm.
  • Recursion reduces the unnecessary calling of the same function with same lines of code again and again.

Disadvantages of using Recursion:

  • Recursion consumes a lot of memory.
  • The recursive functions are computationally exhaustive.
  • It is hard to debug the code.
  • They are not always very useful.

Consider another example of Dart recursive function to get the better understanding of the topic:

Program:

// function to print the nth Fibonacci number 
int Fib( int n )
{
  if( n <= 1 ) // terminating condition 
    return n ;
  else
  return Fib( n - 1 ) + Fib( n - 2 ) ; // recursive call to the function
}
void main( ) 
{
  int n = 10 ;
  print( ' nth Fibonacci number is : ' ) ;
  int fib = Fib( n ) ; // calling the function fib( n )
  print( fib ) ;
}

Output :

nth Fibonacci number is : 
55

Explanation :

Consider the above code in Dart that prints the nth Fibonacci number, here n is 10 and the Fibonacci number at the 10th place is 55. The function Fib( int n ) accepts one argument n of integer type and return type of integer which signifies that the function returns an integer value. The value of n is 1, then simply return n. Else if n is a number more than 1, then the function recursively calls itself and returns the temporary sum. This recursive call is made till n is 1.


Related Topics

Dart Features

Dart is a fully-featured, object-oriented modern language with its roots in the programming language ‘Smalltalk’. It has some of its eminent features similar to the languages such as Java, C#...

4 minutes read.

Dart Types of Functions

Functions are the set of statements intended to perform a specific task. They accept some input from the user, perform the specified computation and generate the output. They are very...

4 minutes read.

Dart Tutorial

Dart is an open-source, structured programming language developed by Google. It is a high-level programming language that emerged in 2011, but its stable version emerged in 2017. It is largely used...

4 minutes read.

Dart Packages

Every programming language has some in-built functions stored inside the header files that makes the task much easier for the programmer. The Dart Packages refer to the compilation of a...

4 minutes read.

Dart Numbers

Dart provides an in-built data type ‘Numbers’ that provides two types of values: intdouble 1. int data type int data type supports integer values, and their size or values range is platform-dependent. Integers...

4 minutes read.

Dart Function

A Dart function is a collective line of code that are targeted to perform a specialised task. Such lines of code (function) can be reused whenever we need to perform...

6 minutes read.

Rust vs Dart

Rust is a system-level programming language that stands next to C ++ in terms of syntax, but offers greater speed and memory security. Dart, on the other hand, is an...

2 minutes read.

Dart If-else statement

In the previous section, we studied about if statements in detail. If – block is executed when the condition evaluates to true, else if the condition evaluates to false, then...

1 minute read.

Dart Comments

Comments are the statements that are used to enhance the readability and understandability of the code. The compiler does not execute these lines. It simply ignores these comments when it scans...

2 minutes read.

Dart HTML DOM

All web pages can be viewed as objects and exist within the browser window. We can access a web page using a web browser and it needs to be connected...

3 minutes read.

Lexical Scope and Closure

Lexical Scope : Lexical scope is a very important term in any programming language. It defines the scope of the variable based on the block it is contained inside. According to...

2 minutes read.

Dart Recursion

Recursion is one of the most important and interesting concepts in any programming language. It can be defined as a process in which a function calls itself directly or indirectly....

5 minutes read.

Dart super keyword

The ' super ' keyword is used to refer to the immediate parent class object of the currently in-use child class. Using this keyword, we can invoke the superclass (...

6 minutes read.

Dart Optional Parameters

Dart functions can have optional parameters with default values. When we create a function, we can specify parameters that calling code can provide; but if the calling code chooses not...

2 minutes read.

Dart Constants

Dart Constants are the objects or variables whose values can’t change or modify during the execution of the program. Their use case is when we want a particular value to...

2 minutes read.

Dart Type Test Operators

Type Test Operators in Dart These operators are used to check the types of expressions at runtime. Dart is a typed language, and we often want to assert that a value...

1 minute read.

Dart Operators Precedence and Associativity

Precedence of operators determines the order in which the operators are evaluated if they are grouped together in a sentence. If two operators share an operand then the one with...

5 minutes read.

Dart this Keyword

The ' this ' keyword, similar to that in Java and C#, refers to an object of the class using it. It points to the current object of the class,...

5 minutes read.

Dart Keywords

Keywords are the reserved words of a programming language, and they have a special meaning that comes defined by the language. These cannot be used as an identifier, and all...

1 minute read.

Dart Standard Input & Output

Standard Input in Dart (stdin): The standard input stream reads data both synchronously and asynchronously from the keyboard.  In Dart programming language, .readLineSync( ) function is used to accept input from the...

3 minutes read.