Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- class MatrixSpiral
- {
- static void Main(string[] args)
- {
- int size = 0;
- bool successParse;
- do
- {
- Console.Write("Enter the rows/cols of the matrix: ");
- successParse = int.TryParse(Console.ReadLine(), out size);
- } while (!successParse);
- int[,] matrix = new int[size, size];
- int count = 1;
- int startRow = 0;
- int startCol = 0;
- int endRow = size - 1;
- int endCol = size - 1;
- do
- {
- //move right
- for (int cols = startCol; cols <= endCol; cols++)
- {
- matrix[startRow, cols] = count;
- count++;
- }
- startRow = startRow + 1;
- //move down
- for (int i = startRow; i <= endRow; i++)
- {
- matrix[i, endCol] = count;
- count++;
- }
- endCol = endCol - 1;
- //move left
- for (int i = endCol; i >= startCol; i--)
- {
- matrix[endRow, i] = count;
- count++;
- }
- endRow = endRow - 1;
- //move up
- for (int i = endRow; i >= startRow; i--)
- {
- matrix[i, startCol] = count;
- count++;
- }
- startCol = startCol + 1;
- } while (size * size >= count);
- //print matrix
- for (int i = 0; i < size; i++)
- {
- for (int j = 0; j < size; j++)
- {
- Console.Write("{0,4}", matrix[i, j]);
- }
- Console.WriteLine();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement