Dart Recursion Function
A recursion function is a function that calls itself in its body.
Finding factorial is a classic example to demonstrate Recursion function. We use the following formula to find factorial of N using recursion function.
n! = n * (n-1)!
which is basically
factorial(n) = n * factorial(n-1)
So, in order to find the result, the function has to delegate itself with a modified value of input.
Example
Now, let us write a factorial()
function, that takes n
as argument, and returns 1
if the n
is 1
, else it computes the product of n
and factorial(n.- 1)
.
main.dart
import 'dart:io'; int factorial(int n) { return n == 1 ? 1 : n * factorial(n - 1); } void main() { print('Enter N'); int N = int.parse(stdin.readLineSync()!); int result = factorial(N); print('Factorial of $N'); print(result); }
Output
Enter N 4 Factorial of 4 24
Explanation
factorial(4) = 4 * factorial(3) | factorial(3) = 3 * factorial(2) | factorial(2) = 2 * factorial(1) | factorial(1) = 1 * factorial(0) | (1)
ADVERTISEMENT
Summary
In this Dart Tutorial, we have learnt what a Recursion function is, and how to use it in Dart, with examples.