Patterns are the repeated decorative design. There is a simple code to write patterns in C#. We can write code to print different types of patterns like star pattern, character pattern and number pattern. Below are the various examples to print patterns of star, character and numeric values. Patterns are a way of designing in sequence or in a logical manner. We can print triangles, pyramids, diamonds, and other symmetries.
Pattern 1: Left Right Angle Triangle
Code:
using System;
public class StarPattern
{
public static void Main(string[] args)
{
int val = 5;
int i, j, k;
for (i=1; i<=val; i++)
{
for (j=1; j<=val-i; j++)
{
Console.Write(" ");
}
for (k=1; k<=i; k++)
{
Console.Write("*");
}
Console.WriteLine("");
}
Console.ReadLine();
}
}
Output:
Pattern 2: Right Angle Triangle
Code:
using System;
public class StarPattern
{
public static void Main(string[] args)
{
for (int row = 1; row <= 6; ++row)
{
for (int col = 1; col <= row; ++col)
{
Console.Write("*");
}
Console.WriteLine();
}
}
}
Output:
Pattern 3: Diamond Star Pattern
Code:
using System;
using System.Collections.Generic;
using System.Text;
namespace DiamondPattern
{
class DiamondPattern
{
static void Main(string[] args)
{
Console.WriteLine("Program for displaying pattern of *.");
Console.Write("Enter the maximum number of *: ");
int n = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("\nHere is the Diamond of Stars\n");
for (int i = 1; i <= n; i++)
{
for (int j = 0; j < (n - i); j++)
Console.Write(" ");
for (int j = 1; j <= i; j++)
Console.Write("*");
for (int k = 1; k < i; k++)
Console.Write("*");
Console.WriteLine();
}
for (int i = n - 1; i >= 1; i--)
{
for (int j = 0; j < (n - i); j++)
Console.Write(" ");
for (int j = 1; j <= i; j++)
Console.Write("*");
for (int k = 1; k < i; k++)
Console.Write("*");
Console.WriteLine();
}
Console.WriteLine();
}
}
}
Output:
Pattern 4: Inverted Right Angle Triangle
Code:
using System;
public class StarPattern
{
public static void Main(string[] args)
{
for (int row=8; row>=1; --row)
{
for (int col=1; col<=row; ++col)
{
Console.Write("*");
}
Console.WriteLine();
}
}
}
Output:
Pattern 5: Pyramid Pattern
Code:
using System;
namespace SampleCode
{
class Program
{
static void Main(string[] args)
{
int x = 6; // Total Number of Lines...
for (int i = 1; i<= x; i++)
{
//loop to print spaces
for (int j = 1; j <= (x - i); j++)
Console.Write(" ");
//loop to print stars
for (int t = 1; t <i * 2; t++)
Console.Write("*");
Console.WriteLine();
}
Console.ReadLine();
}
}
}
Output:
Pattern 6: Parallelogram Pattern
Code:
class Program
{
static void Main(string[] args)
{
int size = 8;
for (int row = 1; row <= size; ++row)
{
for (int col = 1; col <= row; ++col)
{
Console.Write(" ");
}
for (int col = 1; col <= size; ++col)
{
Console.Write("*");
}
Console.WriteLine();
}
Console.ReadLine();
}
}
Output:
Read more:
The Tech Platform
Kommentare