Skip to main content

How to Generate the Fibonacci Sequence in a Batch Script

The Fibonacci sequence is a famous mathematical series where each number is the sum of the two preceding ones, usually starting with 0 and 1. Generating this sequence is a classic programming exercise that is perfect for demonstrating the power of loops, variables, and arithmetic in a batch script.

This guide will teach you how to write a batch script that generates the Fibonacci sequence up to a specified number of terms. You will learn how to use a FOR /L loop and the SET /A command, and you'll see why Delayed Expansion is absolutely essential for this kind of iterative calculation.

note

This is a demonstration of advanced batch scripting logic. The batch command processor is limited to 32-bit integer math and is not fast. This script will fail for large numbers in the sequence. For any serious mathematical task, a more powerful language like PowerShell is recommended.

The Core Logic: The Fibonacci Rule

The Fibonacci sequence is defined by a simple rule: F(n) = F(n-1) + F(n-2)

The sequence begins with the first two numbers, 0 and 1.

  • 0
  • 1
  • 1 (0 + 1)
  • 2 (1 + 1)
  • 3 (1 + 2)
  • 5 (2 + 3)
  • 8 (3 + 5)
  • ...and so on.

Our script will need to keep track of the last two numbers to calculate the next one in the series.

The Tools: FOR /L, SET /A, and Delayed Expansion

To build our generator, we need three key batch scripting features:

  1. FOR /L: A numeric loop that will allow us to repeat our calculation a specific number of times.
  2. SET /A: The arithmetic command, which we will use to perform the addition.
  3. Delayed Expansion: This is critical. Because the values of our numbers will be changing inside the loop, we must use delayed expansion (!Var!) to get their current, up-to-date values on each iteration.

The Script: A Full Fibonacci Sequence Generator

This script will generate the first 20 numbers in the Fibonacci sequence.

@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION

SET "TermsToGenerate=20"

ECHO --- Fibonacci Sequence Generator ---
ECHO Generating the first %TermsToGenerate% terms...
ECHO.

REM --- Handle the first two starting numbers ---
SET "a=0"
SET "b=1"
ECHO %a%
ECHO %b%

REM --- Loop from the 3rd term up to the desired number ---
REM We use a loop from 2 to N-1 because we've already printed two terms.
FOR /L %%i IN (2, 1, %TermsToGenerate%-1) DO (
REM Calculate the next number in the sequence
SET /A "current = !a! + !b!"
ECHO !current!

REM Update the two previous numbers for the next iteration
SET "a=!b!"
SET "b=!current!"
)

ENDLOCAL

How the script works:

  1. SETLOCAL ENABLEDELAYEDEXPANSION: This enables the use of !Var! syntax, which is essential for the loop.
  2. Initialization: We set the two starting numbers of the sequence into variables a and b and print them immediately.
  3. The Loop (FOR /L): The loop is set to run for the remaining number of terms we need to generate.
  4. The Calculation: SET /A "current = !a! + !b!" is the core of the logic. It adds the two previous numbers (!a! and !b!) and stores the result in current. We must use ! here to get their values from the previous iteration.
  5. The "Shift": This is the clever part.
    • SET "a=!b!": The "second to last" number (a) now becomes the "last" number (b).
    • SET "b=!current!": The "last" number (b) now becomes the new current number we just calculated. This prepares the variables for the next iteration of the loop.

Common Pitfalls and How to Solve Them

  • The 32-bit Integer Limit: This is the biggest limitation. The SET /A command uses 32-bit signed integers, which have a maximum value of 2,147,483,647.

    • The 46th Fibonacci number is 1,836,311,903.
    • The 47th Fibonacci number is 2,971,215,073, which will overflow this limit, causing the script to produce an incorrect negative number.
    • Solution: For generating large Fibonacci numbers, you must use a more capable language like PowerShell, which can handle 64-bit integers ([long]) or arbitrarily large numbers ([bigint]).
  • Forgetting Delayed Expansion: If you use %a% and %b% inside the loop, the script will fail completely. The values will not update on each iteration, and it will produce a nonsensical sequence. Solution: This type of iterative calculation is the primary reason delayed expansion exists. It is not optional for this script.

The Superior PowerShell Alternative

This entire batch script can be replaced with a much shorter, faster, and more robust PowerShell one-liner that is not limited by the 32-bit integer boundary.

@ECHO OFF
SET "Terms=50"
ECHO --- Fibonacci with PowerShell (up to %Terms% terms) ---
powershell -Command "$a=0; $b=[bigint]::one; 1..%Terms% | ForEach-Object { $a; $next = $a + $b; $a = $b; $b = $next }"

This version uses PowerShell's [bigint] type, allowing it to calculate enormous Fibonacci numbers without overflowing.

Conclusion

Generating the Fibonacci sequence is a classic programming challenge that is perfectly solvable with pure batch scripting, making it a great exercise for learning advanced concepts.

  • The solution relies on a FOR /L loop to control the number of iterations.
  • SET /A is used for the core addition.
  • Delayed Expansion (!Var!) is absolutely mandatory for the logic to work correctly inside the loop.
  • Be aware of the 32-bit integer limit, which makes the pure-batch method unsuitable for generating more than about 46 terms in the sequence. For larger numbers, PowerShell is the required tool.