using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DrawSpiral
{
class Program
{
int[,] matrix; // Define 2d Array
int arraySize; // Size of Array ex. 5 (5 coulmns and 5 rows)
int currentNumber; // will use this to set value from 1 to number of digits required.
static void Main(string[] args)
{
Console.WriteLine("Enter Array Size :");
int arraysize = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("****************************************");
Program s = new Program(arraysize);
s.SetMatrixValues(arraysize, arraysize);
Console.ReadLine();
}
public Program(int sizeOfArray)
{
this.arraySize = sizeOfArray;
matrix = new int[sizeOfArray, sizeOfArray];
currentNumber = 1;
}
/// <summary>
/// It will set the matrix values starting from 1.
/// </summary>
/// <param name="row">Number of Rows in Array (ex. Size is 5 rows are 5 in array)</param>
/// <param name="column">Number of Columns in Array (ex. Size is 5 columns are 5 in array)</param>
public void SetMatrixValues(int row, int column)
{
int top = 0;
int bottom = row - 1;
int left = 0;
int right = column - 1;
int direction = 0;
while (top <= bottom && left <= right)
{
if (direction == 0)
{
for (int i = top; i <= right; i++)
{
matrix[top, i] = currentNumber;
currentNumber++;
}
top++;
direction = 1;
}
if (direction == 1)
{
for (int i = top; i <= bottom; i++)
{
matrix[i, right] = currentNumber;
currentNumber++;
}
right--;
direction = 2;
}
if (direction == 2)
{
for (int i = right; i >= left; i--)
{
matrix[bottom, i] = currentNumber;
currentNumber++;
}
bottom--;
direction = 3;
}
if (direction == 3)
{
for (int i = bottom; i >= top; i--)
{
matrix[i, left] = currentNumber;
currentNumber++;
}
left++;
}
direction = (direction + 1) % 4;
}
DrawSpiral();
}
private void DrawSpiral()
{
for (int i = 0; i < arraySize; i++)
{
for (int j = 0; j < arraySize; j++)
{
Console.Write(matrix[i, j]);
Console.Write(" ");
}
Console.WriteLine();
}
}
}
}