PRINT A NUMBER PYRAMID AS MENTIONED BELOW :
APPROACH
- The whole pyramid structure can be written in a single nested for loop instead of many separate loops
- A single nested for loop is used along with two flags that help in creating the pyramid structure.One flag moves towards left by 1 and the other to the right by 1.
- If the iteration is at the boundary of the triangle (leftTriangleCreater, rightTriangleCreater) , those can print the Ith Iteration value
- While loop can be used to control the values on the left and right.
- In the left , The while loop iterates till secondelement != middleNumber
- In the right, The while loop iterates till rightsecondElement > i
SOLUTION
using System;
public class Test
{
public static void Main()
{
var number = Console.ReadLine();
int n = Convert.ToInt32(number);
Pattern print = new Pattern();
print.NumberPyramid(n);
}
}
public class Pattern
{
public void NumberPyramid(int n)
{
int totalNoOfIterations = (n*2)-1;
int leftTriangleCreater = n;
int rightTriangleCreater = n;
int middleNumber = 1;
int secondElement;
int rightsecondElement;
for(int i=1;i<=n;i++)
{
secondElement = i+1;
rightsecondElement = middleNumber-1;
for(int j=1;j<=totalNoOfIterations;j++)
{
if(j>=leftTriangleCreater && j<=rightTriangleCreater)
{
if(j==n)
{
Console.Write(middleNumber);
}
else
{
if(j==leftTriangleCreater || j==rightTriangleCreater)
{
Console.Write(i);
}
else
{
if(j<n)
{
while(secondElement!=middleNumber)
{
Console.Write(secondElement);
secondElement++;
}
}
else
{
while(rightsecondElement>i)
{
Console.Write(rightsecondElement);
rightsecondElement--;
}
}
}
}
}
else
{
Console.Write(" ");
}
}
leftTriangleCreater--;
rightTriangleCreater++;
middleNumber=middleNumber+2;
Console.WriteLine();
}
}
}
Comments
Post a Comment