C# PROGRAM PRINT A MULTI-DIMENSIONAL ARRAY IN SNAIL SHELL WAY
C# PROGRAM TO PRINT MATRIX IN A SNAIL SHELL WAY
original post link: http://csharpsense.blogspot.in/2013/02/c-program-print-multi-dimensional-array.html
/**C# PROGRAM TO PRINT MATRIX IN SNAIL SHELL FORMAT**/
//for printing matrix as in the below given format
// 1 2 3 4
// 12 13 14 5
// 11 16 15 6
// 10 9 8 7
// 12 13 14 5
// 11 16 15 6
// 10 9 8 7
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 |
using System; namespace SnailMatrix { class Program { static void Main(string[] args) { //int rows, cols, int size; int a = 0;// b = 1; int i, j, k, count = 0, flag = 0; do { try { Console.WriteLine("\n>>>PROGRAM To PRINT A MULTI-DIMENSIONAL ARRAY walking IN A SNAIL SHELL WAY <<<"); Console.Write("\n Enter the Size of a square Matrix(between 2 to 10):"); size = Convert.ToInt16(Console.ReadLine()); if (size<2||size > 10) //limiting the size of matrix { Console.BackgroundColor = ConsoleColor.DarkRed; //changing background color to red Console.WriteLine("The Size Of Matrix should Be in between 2 and 10."); //System.Console.ResetColor(); ///resetting color Console.ReadKey(); return; } else { flag = 1; int[,] matrix = new int[size, size]; for (k = 1; k < size; k++, a++) { for (i = a, j = a; j < size - k; j++) //lef { matrix[i, j] = ++count; } for (i = a, j = size - k; i < size - k; i++) { matrix[i, j] = ++count; } for (i = size - k, j = size - k; j >= a; j--) { matrix[i, j] = ++count; } for (i = size - (k + 1), j = a; i >= k; i--) { matrix[i, j] = ++count; } } // Console.Write("\n\nt>>> " + size + " * " + size + " MATRIX <<<\nt---------------------------------------\nt"); Console.Write("\n\nt"); for (i = 0; i < size; i++) { for (j = 0; j < size; j++) { if (matrix[i, j] < 10) { Console.Write(" 0" + Convert.ToString(matrix[i, j])); } else { Console.Write(" " + Convert.ToString(matrix[i, j])); } if (j == size - 1) { Console.Write("\nt"); } } } } } catch //to catch exceptions,suppose string entered as a size of matrix { Console.BackgroundColor = ConsoleColor.DarkRed; Console.WriteLine("WARNING:only Number between (2 and 10) is allowed"); Console.ResetColor(); } Console.WriteLine("\n\nt Press any key to exit...."); }while(flag==0); Console.ReadKey(); } } } |
Sample Outputs:
(output:1)
(output : 2) if we are giving size greater than 10 or less than 2
(output : 3) If we are entering input other than int type.
Nice post very helpful
dbakings