Introduction
In this blog, we will look into the Dart Recursion. We will first look at recursion, and then we will see how we can use recursion in a Dart program. The syntax of a recursive function in Dart will also be discussed. If you are new to Dart and are yet to set up your environment for the language, you can check out this article.
Recursion
In any computer language, Recursion refers to a function calling itself. A recursive function invokes itself repeatedly until a specific base condition is reached. Recursion can be used to break down substantial complex problems into smaller subproblems in order to solve them efficiently.
Two main parts of a recursive function are:
- Base Condition: Every time the function call is made, it checks for the base condition. If the base condition evaluates to true, the function returns to the last recursive call.
- Recursive: If the base condition is not satisfied, the rest of the recursive code is rerun.
Syntax
The syntax of a recursive function in Dart is as follows:
void recrusive_function() {
// Base condition to terminate the program
recrusive_function();
// some other code
}
void main() {
recrusive_function();
}
Advantage of Recursion
Following are some of the advantages of using recursion in a program:
- It is helpful in breaking down a huge problem into smaller subproblems.
- Code for a recursive function is generally concise.
- It reduces redundant function calls.
Disadvantage of Recursion
Following are some of the disadvantages of using recursion in a program:
- It generally uses a lot of space.
- It is slower than normal iterations because of the high stack overhead.
- It's slightly harder to debug a recursive function than a non-recursive function.
Example
Now that we have learned what recursion is, let's look at an example to understand the concept better:
// This program computes the sum of first n natural numbers
int sumUptoN(int n) {
// return n if the value of n is less than or equal to 1
if (n == 1) {
return n;
}
// else return n + sum of numbers upto n-1
return n + sumUptoN(n - 1);
}
void main() {
int n = 5;
// calling sumUptoN function to compute the sum of natural numbers upto n
int sum = sumUptoN(n);
print("The Total sum is: $sum");
}
Output:
The Total sum is: 15
Explanation:

The above program computes the sum of natural numbers up to N. It first checks whether the value of n is equal to 1 or not. This is the base condition for this recursive function. If the base condition is satisfied, it returns n. Otherwise, it returns n plus the sum of natural numbers up to n-1.




