C# program to print a diamond pattern:
Let’s learn how to print a diamond pattern in C#. We will write one program that will take the size of the pattern as input from the user and it will print that pattern using * or any other character.
Before we start to write the program, let me show you how the algorithm works.
Algorithm to print a diamond pattern:
A diamond pattern looks as like below:
*
***
*****
*******
*********
*******
*****
***
*
This is a pattern of size 5. We are using blank spaces and * to print this pattern.
If I replace all blank spaces with #, it will look as like below:
####*
###***
##*****
#*******
*********
#*******
##*****
###***
####*
We have to print blank spaces instead of # to print the pattern.
Here,
- For the first line, it prints 4 # and 1 *.
- For the second line, it prints 3 # and 3 *.
- For the third line, it prints 2 # and 5 *.
- For the fourth line, it prints 1 # and 7 * etc.
- Once it reach 0 #, it again starts from 1 to 4.
Let’s write down the program, instead of #, the program will print blank spaces.
C# program to print diamond pattern:
Below is the complete program:
namespace Program
{
class Program
{
static void Main(string[] args)
{
int Size, i, j, Space;
Console.WriteLine("Enter the size: ");
Size = Convert.ToInt32(Console.ReadLine());
Console.WriteLine();
Space = Size - 1;
for (i = 1; i <= Size; i++)
{
for (j = 1; j <= Space; j++)
Console.Write(" ");
Space--;
for (j = 1; j <= 2 * i - 1; j++)
Console.Write("*");
Console.WriteLine();
}
Space = 1;
for (i = 1; i <= Size - 1; i++)
{
for (j = 1; j <= Space; j++)
Console.Write(" ");
Space++;
for (j = 1; j <= 2 * (Size - i) - 1; j++)
Console.Write("*");
Console.WriteLine();
}
}
}
}
- It asks the user to enter the size. This value is stored in the Size variable.
- The Space variable is used to hold the number of blank spaces to print on each line of the pattern.
- We are using two for loop blocks in the program. The first one is to print the first half of the pattern and the second one to print the bottom half of the pattern.
- Inside the loops, it prints the blank spaces and then it prints the stars.
If you run this program, it will print output as like below:
Enter the size:
6
*
***
*****
*******
*********
***********
*********
*******
*****
***
*
Enter the size:
5
*
***
*****
*******
*********
*******
*****
***
*
You might also like:
- C# program to print the area and perimeter of a square
- 3 ways in C# to print Fibonacci triangle
- C# program to print a right-angled triangle using any character or number
- 3 different C# program to print an inverted right-angled triangle
- Different ways in C# to print a hollow square pattern
- C# program to print a star square pattern
- Different ways in C# to print a cross pattern