Introduction
Pattern printing is a popular programming exercise used to understand loops, nested iterations, and logic control in programming.
In this article, you’ll learn how to print a right triangle star pattern using C# WebForms (Visual Studio 2015) — a real-time example that helps you understand nested loop structures.
Pattern to Print
If the user enters 5, the output should be:
*
* *
* * *
* * * *
* * * * *
C# WebForms Real-Time Example
ASPX Page (RightTriangle.aspx)
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="RightTriangle.aspx.cs" Inherits="WebApp.RightTriangle" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Right Triangle Star Pattern</title>
</head>
<body>
<form id="form1" runat="server">
<div style="font-family: Arial; margin: 50px;">
<h2>Right Triangle Star Pattern</h2>
<asp:Label ID="Label1" runat="server" Text="Enter number of rows: " />
<asp:TextBox ID="txtRows" runat="server"></asp:TextBox>
<asp:Button ID="btnPrint" runat="server" Text="Print Pattern" OnClick="btnPrint_Click" />
<br /><br />
<asp:Label ID="lblResult" runat="server" Font-Names="Consolas" Font-Size="Large"></asp:Label>
</div>
</form>
</body>
</html>
Code-Behind (RightTriangle.aspx.cs)
using System;
using System.Text;
namespace WebApp
{
public partial class RightTriangle : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnPrint_Click(object sender, EventArgs e)
{
int rows;
if (int.TryParse(txtRows.Text, out rows) && rows > 0)
{
lblResult.Text = GenerateTriangle(rows);
}
else
{
lblResult.Text = "Please enter a valid positive number.";
}
}
private string GenerateTriangle(int rows)
{
StringBuilder pattern = new StringBuilder();
for (int i = 1; i <= rows; i++)
{
for (int j = 1; j <= i; j++)
{
pattern.Append("* ");
}
pattern.Append("<br/>");
}
return pattern.ToString();
}
}
}
Explanation
The user enters the number of rows in the text box.
When the “Print Pattern” button is clicked:
Nested loops are used:
<br/> is used for line breaks in the web output.
Example Output
For input 5
*
* *
* * *
* * * *
* * * * *
Key Concepts
Nested Loops → Used for pattern control.
StringBuilder → Efficient for string concatenation.
WebForms Output → Line breaks handled using <br/> tag.
Real-Time Use Case
Used in training portals, online coding platforms, or educational web apps.
Helps beginners visualize how nested loops work in C# Web Applications.
Conclusion
This simple yet effective example demonstrates how nested loops work in C# WebForms to generate a right triangle star pattern dynamically.
It strengthens understanding of loops, logic, and dynamic HTML output in ASP.NET WebForms.