Recursive Function: Countdown
Part of the Logic & Flow section of Coddy's Dart journey — lesson 48 of 65.
Now it's time to put recursion into practice with a simple countdown function. This exercise will help you understand how the base case and recursive step work together in real code.
A countdown function starts with a number and prints each number down to zero. Here's how recursion makes this work: if the number is greater than zero, print it and then call the same function with a smaller number. When the number reaches zero, stop.
void countdown(int number) {
if (number <= 0) {
print("Done!");
return; // Base case - stop here
}
print(number);
countdown(number - 1); // Recursive step
}The base case checks if number <= 0 - this is when we stop calling the function. The recursive step calls countdown(number - 1), which is the same problem but with a smaller input, gradually moving us toward the base case.
When you call countdown(3), it prints 3, then calls countdown(2), which prints 2, then calls countdown(1), which prints 1, then calls countdown(0), which prints "Done!" and stops.
Challenge
EasyCreate a program that implements a recursive countdown timer with custom messages. Your program will demonstrate recursion by counting down from a given number and displaying personalized messages at each step.
- Read a string input representing the starting number for the countdown
- Read a string input representing a custom message prefix (e.g.,
"Launch in","Timer", or"Countdown") - Convert the first input to an integer using
int.parse() - Create a recursive function called
customCountdownthat takes two parameters: - An integer
numberrepresenting the current countdown value - A string
messagePrefixfor the custom message - The function should implement the following logic:
- Base case: If the number is less than or equal to 0, print
"Countdown complete!"and return - Recursive step: Print the message prefix followed by the current number, then call itself with
number - 1 - Call the
customCountdownfunction with the converted number and message prefix - Display the results in the exact format shown below
For example, if the inputs are "5" and "Launch in", your program should output:
Starting countdown from: 5
Message prefix: Launch in
========================
Launch in 5
Launch in 4
Launch in 3
Launch in 2
Launch in 1
Countdown complete!If the inputs are "3" and "Timer", your program should output:
Starting countdown from: 3
Message prefix: Timer
========================
Timer 3
Timer 2
Timer 1
Countdown complete!If the inputs are "0" and "Ready", your program should output:
Starting countdown from: 0
Message prefix: Ready
========================
Countdown complete!Your program must implement the recursive customCountdown function that calls itself with a decremented number until it reaches the base case. The function should print the custom message with the current number at each recursive call, demonstrating how recursion breaks down the problem into smaller, identical subproblems. Use string interpolation to format the countdown messages as "$messagePrefix $number".
Cheat sheet
A recursive countdown function demonstrates how recursion works by counting down from a number to zero:
void countdown(int number) {
if (number <= 0) {
print("Done!");
return; // Base case - stop here
}
print(number);
countdown(number - 1); // Recursive step
}The base case checks if number <= 0 to stop the recursion. The recursive step calls the same function with number - 1, moving toward the base case.
When calling countdown(3), it prints 3 → 2 → 1 → "Done!" by making successive recursive calls with decremented values.
Try it yourself
import 'dart:io';
// TODO: Create your customCountdown function here
// Remember to handle the base case (number <= 0) and recursive step
void main() {
// Read input
String? startingNumber = stdin.readLineSync();
String? messagePrefix = stdin.readLineSync();
// Convert string to integer
int number = int.parse(startingNumber!);
// Display initial information
print('Starting countdown from: $number');
print('Message prefix: $messagePrefix');
print('========================');
// TODO: Call your customCountdown function here
// Remember to handle null safety for messagePrefix
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Advanced List Manipulation
List Properties: first & lastList State: isEmpty & isNotEmpReversing a ListAdding to a List: insertList Removal: removeWhereFinding in a List: indexOfSorting a ListShuffling a ListRecap - List Organizer4Advanced Map Manipulation
Iterating Over a MapChecking for Keys and ValuesMap Properties: keys & valuesConditional Add: putIfAbsentRemoving Entries from a MapNested MapsRecap - Inventory Update7Advanced Functions
Anonymous FunctionsPassing Functions as ArgumentsUnderstanding ClosuresIntroduction to RecursionRecursive Function: CountdownRecursive Function: FactorialRecap - List Processor2Functional List Operations
Transforming with 'map'Filtering with 'where'Using '.toList()'Checking Conditions with 'any'Conditions with 'every'Finding with 'firstWhere'Recap - Data Filtering5Project: Shopping Cart Calc
Project SetupAdding Items to the Cart3Sets
What is a Set?Creating a SetAdding and Removing from SetsChecking for Elements in a SetConverting a List to a SetSet UnionSet IntersectionSet DifferenceRecap - Unique Guest List