Monthly Archives: January 2025
C# || How To Get First X Rows of Pascal’s Triangle Using C#

The following is a module with functions which demonstrates how to get first x rows of Pascal’s Triangle using C#.
1. Pascal’s Triangle – Problem Statement
Given an integer numRows, return the first numRows of Pascal’s triangle.
In Pascal’s triangle, each number is the sum of the two numbers directly above it as shown:
Example 1:
Input: numRows = 5
Output: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]
Example 2:
Input: numRows = 1
Output: [[1]]
2. Pascal’s Triangle – Solution
The following is a solution which demonstrates how to convert get first x rows of Pascal’s Triangle.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
// ============================================================================ // Author: Kenneth Perkins // Date: Jan 1, 2025 // Taken From: http://programmingnotes.org/ // File: Solution.cs // Description: Demonstrates how to get first x rows of Pascal's Triangle // ============================================================================ public class Solution { public IList<IList<int>> Generate(int numRows) { var results = new List<IList<int>>(); if (numRows < 1) { return results; } // Add the initial row results.Add(new List<int>() { {1} }); for (int row = 2; row <= numRows; ++row) { var previousRow = results[results.Count - 1]; var currentRow = new List<int>(); currentRow.Add(previousRow[0]); for (int index = 1; index < row - 1; ++index) { var value = previousRow[index - 1] + previousRow[index]; currentRow.Add(value); } currentRow.Add(previousRow[previousRow.Count - 1]); results.Add(currentRow); } return results; } }// http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
Once compiled, you should get this as your output for the example cases:
[[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]
[[1]]