Dart Recursion
Dart Recursion
Recursion means that a function calls itself.
It is a way to solve a big problem by breaking it into smaller problems of the same kind.
This function counts down from a number to 1, by calling itself with a smaller number each time:
Example
void countdown(int n) {
if (n == 0) {
print('Go!');
return;
}
print(n);
countdown(n - 1);
}
void main() {
countdown(3);
}
Try it Yourself »
Result:
3
2
1
Go!
The Base Case
Every recursive function needs a base case.
The base case is the condition where the function stops calling itself.
In the example above, the base case is n == 0.
Every other call is a recursive case, where the function calls itself with a value that is closer to the base case.
Note: Without a base case, the function calls itself forever, and the program crashes with an error.
Always check that each call moves closer to the base case.
Sum of Numbers
This function adds all numbers from 1 to n:
Example
int sum(int n) {
if (n == 1) {
return 1;
}
return n + sum(n - 1);
}
void main() {
print(sum(5));
print(sum(10));
}
Try it Yourself »
Result:
15
55
Example Explained
When we call sum(5), this is what happens:
sum(5) = 5 + sum(4)
sum(4) = 4 + sum(3)
sum(3) = 3 + sum(2)
sum(2) = 2 + sum(1)
sum(1) = 1
When sum(1) returns 1, each waiting call can finish.
The result is 5 + 4 + 3 + 2 + 1, which is 15.
Factorial
The factorial of a number is the number multiplied by every whole number below it, down to 1.
For example, the factorial of 4 is 4 * 3 * 2 * 1, which is 24.
Factorial is a classic example of recursion:
Example
int factorial(int n) {
if (n <= 1) {
return 1;
}
return n * factorial(n - 1);
}
void main() {
print(factorial(4));
print(factorial(6));
}
Try it Yourself »
Result:
24
720
The same function can be written in one line with the arrow syntax and the conditional operator:
Example
int factorial(int n) => n <= 1 ? 1 : n * factorial(n - 1);
void main() {
print(factorial(5));
}
Try it Yourself »
Result:
120
Recursion With a List
Recursion also works with lists.
This function adds all the numbers in a list, by taking the first item and calling itself with the rest of the list:
Example
int total(List<int> numbers) {
if (numbers.isEmpty) {
return 0;
}
return numbers.first + total(numbers.sublist(1));
}
void main() {
var scores = [10, 25, 40];
print(total(scores));
}
Try it Yourself »
Result:
75
The base case is an empty list, which has a total of 0.
Recursion or Loop?
Most recursive functions can also be written with a loop.
This loop gives the same result as the recursive sum() function:
Example
int sum(int n) {
var result = 0;
for (var i = 1; i <= n; i++) {
result += i;
}
return result;
}
void main() {
print(sum(5));
}
Try it Yourself »
Result:
15
A loop is often faster and uses less memory.
Recursion is useful when the problem itself is built of smaller copies, like folders inside folders, or a family tree.