Introduction
Printing pattern programs is a common programming exercise for understanding loops and conditional logic in C#. A pyramid pattern is a good example because it requires controlling both spaces and asterisks based on the current row.
In this example, we will print a centered pyramid using * characters. The value 7 represents the number of rows.
The expected output is:
*
***
*****
*******
*********
***********
*************
C# Pyramid Pattern Program
The following program uses nested for loops to print the pyramid.
using System;
public class Program
{
public static void Main()
{
PrintPyramid(7);
}
static void PrintPyramid(int n)
{
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= (n * 2 - 1); j++)
{
if (j <= n - i || j >= n + i)
Console.Write(" ");
else
Console.Write("*");
}
Console.WriteLine();
}
}
}
How the Logic Works
The method accepts the number of rows through the n parameter:
PrintPyramid(7);
Therefore, the program creates a pyramid with seven rows.
The outer loop controls the rows:
for (int i = 1; i <= n; i++)
For n = 7, the loop executes seven times.
The inner loop controls the positions in each row:
for (int j = 1; j <= (n * 2 - 1); j++)
A pyramid with n rows requires a maximum width of:
2 × n - 1
For seven rows:
2 × 7 - 1 = 13
So every row is evaluated across 13 character positions.
Understanding the Condition
The most important part of the program is:
if (j <= n - i || j >= n + i)
Console.Write(" ");
else
Console.Write("*");
The condition determines whether the current position should contain a space or an asterisk.
For the first row:
i = 1
n = 7
The star positions are:
7
For the second row:
i = 2
The star positions are:
6 7 8
For the third row:
i = 3
The star positions are:
5 6 7 8 9
The number of stars increases by two for every new row.
Dry Run
For n = 7, the program produces the following pattern:
Join the conversation! Your thoughts help the community grow.