Menu
Coddy logo textTech

Recursive Function: Factorial

Part of the Logic & Flow section of Coddy's Dart journey — lesson 49 of 65.

The factorial of a number is a classic mathematical operation that's perfect for demonstrating recursion. The factorial of a positive integer n (written as n!) is the product of all positive integers from 1 to n. For example, 5! = 5 × 4 × 3 × 2 × 1 = 120.

What makes factorial ideal for recursion is that it naturally breaks down into smaller, identical problems. To calculate 5!, you can think of it as 5 × 4!. And 4! is just 4 × 3!, and so on. This pattern continues until you reach 1!, which equals 1.

int factorial(int n) {
  if (n <= 1) {
    return 1; // Base case
  }
  
  return n * factorial(n - 1); // Recursive step
}

The base case stops the recursion when n <= 1, returning 1. The recursive step multiplies the current number by the factorial of the next smaller number. When you call factorial(5), it returns 5 * factorial(4), which returns 5 * 4 * factorial(3), and so on until it reaches the base case.

This approach demonstrates how recursion elegantly solves problems by reducing them to simpler versions of the same problem, making complex calculations feel natural and intuitive.

challenge icon

Challenge

Easy

Create a program that calculates factorials for multiple numbers using recursion. Your program will demonstrate the recursive factorial function by processing a list of numbers and computing their factorials.

  1. Read a string input containing numbers separated by commas (e.g., "3,5,0,7")
  2. Split the input string into individual numbers and convert each to an integer
  3. Create a recursive function called factorial that takes an integer parameter n
  4. The factorial function should implement the following logic:
    • Base case: If n is less than or equal to 1, return 1
    • Recursive step: Return n multiplied by factorial(n - 1)
  5. For each number in the input list, calculate its factorial using your recursive function
  6. Display the results showing each number and its corresponding factorial
  7. Calculate and display the sum of all the factorial results

For example, if the input is "4,3,2", your program should output:

Factorial Calculator
====================
Processing numbers: [4, 3, 2]
====================
Factorial Results:
4! = 24
3! = 6
2! = 2
====================
Sum of all factorials: 32
Calculation completed successfully

If the input is "5,0,1", your program should output:

Factorial Calculator
====================
Processing numbers: [5, 0, 1]
====================
Factorial Results:
5! = 120
0! = 1
1! = 1
====================
Sum of all factorials: 122
Calculation completed successfully

If the input is "6", your program should output:

Factorial Calculator
====================
Processing numbers: [6]
====================
Factorial Results:
6! = 720
====================
Sum of all factorials: 720
Calculation completed successfully

Your program must implement the recursive factorial function that calls itself with decremented values until it reaches the base case. The function should demonstrate how recursion breaks down the factorial calculation into smaller, identical subproblems. Use string interpolation to format the factorial results as "$n! = $result". Remember that 0! equals 1 by mathematical definition, which your base case should handle correctly.

Cheat sheet

The factorial of a positive integer n (written as n!) is the product of all positive integers from 1 to n. For example, 5! = 5 × 4 × 3 × 2 × 1 = 120.

Factorial is ideal for recursion because it breaks down into smaller, identical problems: 5! = 5 × 4!, and 4! = 4 × 3!, continuing until reaching 1! = 1.

int factorial(int n) {
  if (n <= 1) {
    return 1; // Base case
  }
  
  return n * factorial(n - 1); // Recursive step
}

The base case stops recursion when n <= 1, returning 1. The recursive step multiplies the current number by the factorial of the next smaller number.

Try it yourself

import 'dart:io';

// TODO: Create your recursive factorial function here

void main() {
  // Read input string containing comma-separated numbers
  String? input = stdin.readLineSync();
  
  // Split the input and convert to integers
  List<int> numbers = input!.split(',').map((str) => int.parse(str.trim())).toList();
  
  // TODO: Write your code below to:
  // 1. Process each number using your factorial function
  // 2. Calculate the sum of all factorials
  // 3. Display the results in the required format
  
  print("Factorial Calculator");
  print("====================");
  print("Processing numbers: $numbers");
  print("====================");
  print("Factorial Results:");
  
  // TODO: Calculate and display factorial results here
  
  print("====================");
  // TODO: Display sum of all factorials
  print("Calculation completed successfully");
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow