Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * Unit 6. Loops
- * Exercise 6.14.
- *
- * 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.
- *
- * Author: Pavel Petrov (AN: 9001944)
- *
- */
- using System;
- using System.Collections.Generic;
- class SpiralMatrix
- {
- static void Main()
- {
- // The matrix size
- int n = 0;
- int currentValue = 1;
- int pos = -1; // Direction 1: ascending, -1: descending
- int row = 0, col = 0; // Current row, col
- // User choice of matrix size
- Console.Write("Enter the matrix size: ");
- bool isInteger = Int32.TryParse(Console.ReadLine(), out n);
- Console.WriteLine();
- if (isInteger)
- {
- int[,] matrix = new int[n, n]; // The matrix
- int maxDirections = (n * 2) - 1; // Total number of moves
- int size = n; // Size of current move
- string[] directions = { "up", "right", "down", "left" }; // Directions (for clarity)
- for (int currentDirection = 1; currentDirection <= maxDirections; currentDirection++)
- {
- if (currentDirection % 2 == 0)
- {
- size--; // Decrease size of next move
- }
- else
- {
- pos *= -1; // Change direction of move
- }
- // Fill the matrix
- for (int i = 0; i < size; i++)
- {
- switch (directions[currentDirection % 4])
- {
- case "right":
- case "left":
- col += pos;
- matrix[row, col - 1] = currentValue;
- break;
- case "down":
- case "up":
- row += pos;
- matrix[row, col - 1] = currentValue;
- break;
- }
- // Next member
- currentValue++;
- }
- }
- // Print the matrix
- for (int i = 0; i < n; i++)
- {
- Console.WriteLine();
- for (int j = 0; j < n; j++)
- {
- Console.Write("{0,4}", matrix[i, j]);
- }
- Console.WriteLine();
- }
- Console.WriteLine();
- }
- else
- {
- Console.WriteLine("The matrix size must be a integer number only!!!");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement