Recursion in Dart
Dart supports recursive functions. Here’s a classic example.
To run the program, save it as recursion.dart
and use the dart
command:
In this Dart example, we’ve implemented the same recursive factorial and Fibonacci functions as in the original code. The main differences are:
We use
import 'dart:io';
instead ofimport "fmt"
for standard I/O operations.The
fact
function is defined outside ofmain
, and its syntax is slightly different from the original, usingint
for type annotations.In Dart, we don’t need to explicitly declare the type of a closure before defining it. We can directly assign the anonymous function to
fib
.We use
print
instead offmt.Println
for output.
The behavior and output of the program remain the same as the original example, demonstrating how recursion works in Dart.