Advertisement
svetlai

Fill The Matrix Example

Feb 11th, 2015
185
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.47 KB | None | 0 0
  1. namespace FillTheMatrix
  2. {
  3.     using System;
  4.  
  5.     /// <summary>
  6.     /// Problem 1. Fill the matrix
  7.     /// Write a program that fills and prints a matrix of size `(n, n)` as shown below:
  8.     /// </summary>
  9.     public class FillTheMatrix
  10.     {
  11.         public static void Main()
  12.         {
  13.         int n = 4;
  14.             int[,] matrix = new int[n, n];
  15.  
  16.             for (int row = 0; row < matrix.GetLength(0); row++)
  17.             {
  18.                 for (int col = 0; col < matrix.GetLength(1); col++)
  19.                 {    
  20.                     // 1   2   3   4
  21.                     // 5   6   7   8
  22.                     // 9   10  11  12
  23.                 // 13  14  15  16  
  24.                     // matrix[row, col] = row * n + col + 1;
  25.  
  26.             // swicth row and col and you'll get:
  27.                     // 1  5  9   13
  28.                 // 2  6  10  14
  29.                 // 3  7  11  15
  30.                 // 4  8  12  16  
  31.                     matrix[col, row] = row * n + col + 1;
  32.  
  33.             // alternative way:
  34.                     // matrix[row, col] = row + col * n + 1;
  35.                 }
  36.             }
  37.         }
  38.  
  39.         public static void PrintMatrix(int[,] matrix)
  40.         {
  41.             for (int row = 0; row < matrix.GetLength(0); row++)
  42.             {
  43.                 for (int col = 0; col < matrix.GetLength(1); col++)
  44.                 {
  45.                     Console.Write("{0,3}", matrix[row, col]);
  46.                 }
  47.  
  48.                 Console.WriteLine();
  49.             }
  50.         }
  51.     }
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement