Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * * Write a program that reads a positive integer number N (N < 20) from console and outputs in the console the numbers 1 ... N numbers arranged as a spiral.
- Example for N = 4
- *
- */
- using System;
- class NumbersArrangedAsSpiral
- {
- static void Main()
- {
- byte numberN;
- string invalidInput = "Please enter a valid number 0 < N < 20!" + Environment.NewLine;
- Console.WriteLine("Enter a value for N:");
- while (!(byte.TryParse(Console.ReadLine(), out numberN) && numberN > 0 && numberN < 20))
- {
- Console.WriteLine(invalidInput);
- Console.WriteLine("Enter a value for N:");
- }
- Console.WriteLine();
- int[,] spiralMatrix = new int[numberN, numberN];
- byte rows = 0;
- byte columns = 0;
- int elementsCount = 0;
- byte currentRow = 0;
- byte currentColumn = 0;
- int maxRows = numberN - 1;
- int maxColumns = maxRows;
- while (!(elementsCount >= numberN * numberN))
- {
- for (int i = currentColumn; i <= maxColumns; i++)
- {
- elementsCount++;
- spiralMatrix[currentRow, i] = elementsCount;
- }
- currentRow++;
- for (int i = currentRow; i <= maxRows; i++)
- {
- elementsCount++;
- spiralMatrix[i, maxColumns] = elementsCount;
- }
- maxColumns--;
- for (int i = maxColumns; i >= currentColumn; i--)
- {
- elementsCount++;
- spiralMatrix[maxRows, i] = elementsCount;
- }
- maxRows--;
- for (int i = maxRows; i >= currentRow; i--)
- {
- elementsCount++;
- spiralMatrix[i, currentColumn] = elementsCount;
- }
- currentColumn++;
- }
- for (rows = 0; rows < numberN; rows++)
- {
- for (columns = 0; columns < numberN; columns++)
- {
- Console.Write("{0,5}", spiralMatrix[rows, columns]);
- }
- Console.WriteLine();
- }
- Console.WriteLine();
- Main();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment