×

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 Inheritance

Inheritance is a promising concept of any programming language. It is a property by which a class inherits the property of another class. Moreover, the class deriving the properties of...

5 minutes 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.

Metadata in Dart

Metadata is often referred to as the data about the data. It is a  piece of data about a basic piece of data. In the case of a Dart program,...

2 minutes read.

Dart Method Overriding

Before understanding method overriding, it is important to clear the concept of polymorphism. Polymorphism is derived from two Greek words 'Poly' which means many and 'morphs' which means many forms....

5 minutes read.

Dart Strings

Strings data type in Dart A Dart string is a sequence of characters with an encoding of UTF-16. The text associated with string data type is enclosed withing single (‘  ’)...

3 minutes read.

Dart Assignment Operator

Assignment operators are the operators that assign value to the variables. The value on the right-hand side is assigned to the variable on the left-hand side. We can also use...

4 minutes read.

Dart Objects

Apart from the built-in data types, Dart offers some other data types that have a special role to play. One of them is Objects.  Objects Objects are the foundation of the...

3 minutes read.

Typedef in Dart

In Dart, typedef is used to generate a function type that we can use as a type annotation for declaring variables and return types of the function type. An alias...

4 minutes read.

Golang vs Dart

Go is the procedural programming language. It was founded in 2007 by Robert Griesemer, Rob Pike, and Ken Thompson at Google but was launched in 2009 as the language of...

2 minutes read.

Soundness in Dart

What is soundness? Soundness ensures that the program never comes across any invalid state that may lead to abrupt termination of the program. As its name suggests it ensures perfect type...

4 minutes read.

Dart Basics

Dart, as earlier mentioned multiple times, is very similar to C, C++ and Java. It is an object-oriented, garbage collecting and class-based programming language. Let’s look further and see what Dart has...

10 minutes read.

Dart Classes

Dart is an object – oriented programming language that supports all the object-oriented programming concepts such as classes, objects, inheritance, data abstraction and data encapsulation. A class can be defined as...

8 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 Built-in Data Types

A data type defines the type of value a variable can hold, such as integer, double, or string.  Dart supports two data types:  1. Built-in data types : These are the data...

1 minute 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 lists data type

The most important data type in any programming language is an ordered list of elements, an array. Dart lists resemble JavaScript array lists. Example,               var...

7 minutes read.

Dart Symbols

Symbols data type in Dart A symbol is an object that is the representation of an operator or identifier in Dart. These are compile-time constants.  They are used in APIs that refer...

1 minute read.

Dart Arithmetic Operators

Arithmetic Operators comprises of all the operators that are used to perform arithmetic operations such as addition, subtraction, multiplication, division, etc. They are binary operators that work upon two operands. Consider A...

2 minutes read.

Abstract Classes in Dart

Abstract classes in Dart are those classes that only contain abstract methods  (methods that do not contain any implementation). These classes are specifically designed for the purpose of inheritance. We...

4 minutes read.

Common Collection Methods

Most of the programming languages have arrays as a way to list items together. However, Dart has a collection of data structures similar to array. These are supported by the...

3 minutes read.