Concept: Pascal’s Triangle
Pascal’s Triangle is a triangular array of numbers where each number is the sum of the two numbers directly above it.
Example for 5 rows
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
WebForms Real-Time Example
ASPX Page (PascalTriangle.aspx)
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="PascalTriangle.aspx.cs" Inherits="WebApp.PascalTriangle" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Pascal’s Triangle Example</title>
</head>
<body>
<form id="form1" runat="server">
<div style="font-family:Arial; margin:50px;">
<h2>Generate Pascal’s Triangle</h2>
<asp:Label ID="Label1" runat="server" Text="Enter number of rows:" />
<asp:TextBox ID="txtRows" runat="server"></asp:TextBox>
<asp:Button ID="btnGenerate" runat="server" Text="Generate" OnClick="btnGenerate_Click" />
<br /><br />
<asp:Label ID="lblResult" runat="server" />
</div>
</form>
</body>
</html>
Code-Behind (PascalTriangle.aspx.cs)
using System;
using System.Text;
namespace WebApp
{
public partial class PascalTriangle : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnGenerate_Click(object sender, EventArgs e)
{
int rows;
if (int.TryParse(txtRows.Text, out rows) && rows > 0)
{
lblResult.Text = GeneratePascalTriangle(rows);
}
else
{
lblResult.Text = "Please enter a valid positive number.";
}
}
private string GeneratePascalTriangle(int rows)
{
int[,] triangle = new int[rows, rows];
StringBuilder sb = new StringBuilder();
for (int i = 0; i < rows; i++)
{
for (int j = 0; j <= i; j++)
{
// First and last values in a row are 1
if (j == 0 || j == i)
triangle[i, j] = 1;
else
triangle[i, j] = triangle[i - 1, j - 1] + triangle[i - 1, j];
sb.Append(triangle[i, j] + " ");
}
sb.Append("<br/>");
}
return sb.ToString();
}
}
}
Explanation
Output Example
If the user enters 5, output will be:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1