Pascal's Triangle is a triangular array of numbers where each number is the sum of the two numbers directly above it. The edges are always 1. It has deep connections to combinations (C(n, r)), probability, and the Binomial Theorem. Generating it in Batch is an excellent exercise in 2D array logic and nested loops.
In this guide, we will demonstrate how to build and display Pascal's Triangle row by row.
The Strategy: The Two-Row Buffer
- Start with Row 0:
[1]. - For each subsequent Row
n:- The first and last elements are always
1. - Each inner element is the sum of
Row[n-1][j-1]andRow[n-1][j].
- The first and last elements are always
Implementation Script
@echo off
setlocal enabledelayedexpansion
set /p "rows=Enter number of rows: "
set /a "maxIndex=rows - 1"
echo.
echo --- PASCAL'S TRIANGLE (%rows% rows^) ---
echo.
for /L %%n in (0,1,%maxIndex%) do (
set "line="
for /L %%k in (0,1,%%n) do (
if %%k EQU 0 (
set "P_%%n_%%k=1"
) else if %%k EQU %%n (
set "P_%%n_%%k=1"
) else (
set /a "prevRow=%%n - 1"
set /a "prevCol=%%k - 1"
:: Build variable names using intermediate variables
set "varA=P_!prevRow!_!prevCol!"
set "varB=P_!prevRow!_%%k"
:: Use call trick to resolve double-delayed expansion
for %%A in (!varA!) do for %%B in (!varB!) do (
set /a "P_%%n_%%k=!%%A! + !%%B!"
)
)
set "line=!line! !P_%%n_%%k!"
)
echo !line!
)
pauseExample of output with 10 rows:
Enter number of rows: 10
--- PASCAL'S TRIANGLE (10 rows) ---
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1Why Generate Pascal's Triangle?
- Combinatorics: The n-th row, k-th position gives you
C(n, k)directly. This is a visual way to compute combinations without the factorial formula. - Probability: Pascal's Triangle is used to calculate binomial probabilities (e.g., the probability of getting exactly 3 heads in 5 coin flips).
- Pattern Discovery: The triangle contains hidden patterns, including Fibonacci numbers (diagonal sums), powers of 2 (row sums), and powers of 11 (row concatenation for small rows).
Important Limitations
Best Practices
- Memory Optimization: You only need the previous row to calculate the current row. Instead of storing all rows, you can use two buffers (
PREV_andCURR_) and swap them after each row. - Centering: To visually center the triangle, add
(totalRows - currentRow)spaces before each line.
Conclusion
Generating Pascal's Triangle is a beautiful demonstration of mathematical patterns brought to life through code. By combining 2D array logic with simple addition, you create a structure that reveals deep connections between numbers. This exercise strengthens your mastery of nested loops and variable namespacing, providing the skills needed to build complex mathematical visualizations and analysis tools in Batch.