Generating a Number Triangle Pattern in C#: A Nested Loop Example

Learn how to generate various number triangle patterns in C# using nested loops. This tutorial provides a C# program that creates a symmetrical number triangle, explains the logic behind the nested loops, and demonstrates a common programming exercise for practicing loop control and pattern generation.



Generating a Number Triangle in C#

This program demonstrates how to generate a number triangle pattern in C#. Number triangles are common programming exercises that help illustrate the use of nested loops.

Understanding the Number Triangle Pattern

A number triangle is a pattern where each row has an increasing number of digits, typically forming a symmetrical pattern. The example below generates a triangle where each row contains consecutive numbers, mirrored around a central number.

C# Code to Generate the Number Triangle


using System;

public class NumberTriangleExample {
    public static void Main(string[] args) {
        Console.Write("Enter the range: ");
        int n = int.Parse(Console.ReadLine());
        // ... (nested for loops to generate and print the triangle pattern) ...
    }
}

Explanation

The program uses nested `for` loops. The outer loop iterates through each row. The inner loops handle spacing and printing numbers for each row. The first inner loop adds spaces for alignment. The second and third loops print the increasing and then decreasing sequence of numbers to create the symmetrical pattern.