Advertisement
dimipan80

Fill the Matrix

May 9th, 2015
308
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.10 KB | None | 0 0
  1. /* Write two programs that fill and print a matrix of size N x N. Filling a matrix in the regular pattern (top to bottom and left to right) is boring. */
  2.  
  3. namespace _01.FillTheMatrix
  4. {
  5.     using System;
  6.  
  7.     class FillTheMatrix
  8.     {
  9.         static void Main(string[] args)
  10.         {
  11.             Console.Write("Enter a Positive Integer for size of matrix: ");
  12.             int size = int.Parse(Console.ReadLine());
  13.  
  14.             Console.WriteLine(@"Please choose a type of the regular pattern to fill:
  15. 1 --> top to bottom
  16. 2 --> left to right
  17. ");
  18.             int numChoice;
  19.             do
  20.             {
  21.                 Console.Write("Enter the number of your choice: ");
  22.             } while (!int.TryParse(Console.ReadLine(), out numChoice) || numChoice < 1 || numChoice > 2);
  23.  
  24.             int[,] matrix = new int[size, size];
  25.             FillTheMatrixByChoicenRegularPattern(matrix, numChoice);
  26.             PrintTheMatrix(matrix);
  27.         }
  28.  
  29.         private static void FillTheMatrixByChoicenRegularPattern(int[,] matrix, int pattern)
  30.         {
  31.             int n = matrix.GetLength(0);
  32.             for (int row = 0; row < matrix.GetLength(0); row++)
  33.             {
  34.                 for (int col = 0; col < matrix.GetLength(1); col++)
  35.                 {
  36.                     if (pattern == 2 && col % 2 != 0)
  37.                     {
  38.                         matrix[row, col] = (n * (col + 1)) - row;
  39.                     }
  40.                     else
  41.                     {
  42.                         matrix[row, col] = (n * col) + row + 1;
  43.                     }
  44.                 }
  45.             }
  46.         }
  47.  
  48.         private static void PrintTheMatrix(int[,] matrix)
  49.         {
  50.             Console.WriteLine("Your filled matrix is: ");
  51.             Console.WriteLine();
  52.             for (int row = 0; row < matrix.GetLength(0); row++)
  53.             {
  54.                 for (int col = 0; col < matrix.GetLength(1); col++)
  55.                 {
  56.                     Console.Write("{0,4}", matrix[row, col]);
  57.                 }
  58.                 Console.WriteLine();
  59.             }
  60.             Console.WriteLine();
  61.         }
  62.     }
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement