Menu
×
   ❮   
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP C C++ C# AWS W3.CSS HOW TO BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS DSA TYPESCRIPT ANGULAR ANGULARJS GIT POSTGRESQL SQLITE MONGODB ASP AI R GO KOTLIN SWIFT SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE INTRO TO PROGRAMMING HTML & CSS BASH RUST DART PLAYWRIGHT TOOLS MATH SHEETS POWER BI

Dart Tutorial

Dart HOME Dart Intro Dart Get Started Dart Syntax Dart Output Dart Comments Dart Variables Dart final and const Dart Data Types Dart Numbers Dart Strings Dart String Interpolation Dart String Methods Dart Booleans Dart Type Conversion Dart Null Safety Dart late Dart Operators Dart Arithmetic Dart Assignment Dart Comparison Dart Logical Dart Type Test Dart Null Operators Dart Cascade Dart If...Else Dart Switch Dart While Loop Dart For Loop Dart Break/Continue

Dart Collections

Dart Lists Dart Access List Items Dart Change List Items Dart Loop Lists Dart List Methods Dart Sets Dart Maps Dart Access Map Items Dart Loop Maps Dart Collection if/for Dart Spread Operator

Dart Functions

Dart Functions Dart Parameters Dart Named Parameters Dart Return Values Dart Arrow Functions Dart Anonymous Functions Dart Closures Dart Scope Dart Recursion

Dart Classes

Dart OOP Dart Classes/Objects Dart Constructors Dart Named Constructors Dart Factory Constructors Dart Getters and Setters Dart Static Members Dart Inheritance Dart Abstract Classes Dart Interfaces Dart Mixins Dart Extension Methods Dart Enums Dart Generics

Dart 3 Features

Dart Records Dart Patterns Dart Switch Expressions Dart Sealed Classes Dart Class Modifiers

Dart Errors

Dart Exceptions Dart Custom Exceptions

Dart Async

Dart Async Intro Dart Futures Dart async/await Dart Streams Dart Isolates

Dart Libraries

Dart Imports Dart Packages Dart Math Dart Dates Dart JSON Dart RegExp Dart User Input Dart Files Dart Testing

Dart Examples

Dart Examples Dart Exercises


Dart Recursion


Share

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.



Free account

Track your progress

XP earned 0 Day streak 0 Spaces 0 League —

New

Learn in Adventure Mode W3Schools Adventure App

Coding fundamentals as bite-sized lessons and challenges.

×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookies and privacy policy.

Copyright 1999-2026 by W3Schools. All Rights Reserved. W3Schools is Powered by W3.CSS.