In almost every interview, the interviewer will ask you to write a program to print diamond/triangle with the stars or numbers.
In this, we will see how to print a triangle and diamond.
Pattern 1 - Diamond shape with the * symbol. (DiamondOne() method)
Diamond shape: we have to use two for loops and under that, two more for loops to print the * and space.
Example:
- private static void DiamondOne()
- {
- int i, j, count = 1, number;
- Console.Write("Enter number of rows:");
- number = int.Parse(Console.ReadLine());
- count = number - 1;
- for (j = 1; j <= number; j++)
- {
- for (i = 1; i <= count; i++)
- Console.Write(" ");
- count--;
- for (i = 1; i <= 2 * j - 1; i++)
- Console.Write("*");
- Console.WriteLine();
- }
- count = 1;
- for (j = 1; j <= number - 1; j++)
- {
- for (i = 1; i <= count; i++)
- Console.Write(" ");
- count++;
- for (i = 1; i <= 2 * (number - j) - 1; i++)
- Console.Write("*");
- Console.WriteLine();
- }
- Console.ReadLine();
- }
O/P
Pattern 2 - Triangle shape with the * symbol (TriangleTwo() Method).
Triangle shape: if we remove the second outer for loop, then it will print in the triangle shape.
Example:
- private static void TriangleTwo()
- {
- int number, i, j, count = 1;
- Console.Write("Enter number of rows:");
- number = int.Parse(Console.ReadLine());
- count = number - 1;
- for (j = 1; j <= number; j++)
- {
- #region Printing Space
- for (i = 1; i <= count; i++)
- Console.Write(" ");
- count--;
- #endregion
- for (i = 1; i <= 2 * j - 1; i++)
- Console.Write("*");
- Console.WriteLine();
- }
- Console.ReadLine();
- }
O/P
Pattern 3 - Triangle shape with the * symbol (TriangleOne() Method).
And again, if we remove the first for loop region highlighted in the yellow color, then, the triangle will be printed in the below shape.
Code
- private static void TriangleOne()
- {
- int number, i, j, count = 1;
- Console.Write("Enter number of rows:");
- number = int.Parse(Console.ReadLine());
- count = number - 1;
- for (j = 1; j <= number; j++)
- {
- for (i = 1; i <= 2 * j - 1; i++)
- Console.Write("*");
- Console.WriteLine();
- }
- Console.ReadLine();
- }
In similar fashion, we can print the same by using numbers. Replace * with numbers and it will work.