Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- namespace FillTheMatrix
- {
- using System;
- /// <summary>
- /// Problem 1. Fill the matrix
- /// Write a program that fills and prints a matrix of size `(n, n)` as shown below:
- /// </summary>
- public class FillTheMatrix
- {
- public static void Main()
- {
- int n = 4;
- int[,] matrix = new int[n, n];
- for (int row = 0; row < matrix.GetLength(0); row++)
- {
- for (int col = 0; col < matrix.GetLength(1); col++)
- {
- // 1 2 3 4
- // 5 6 7 8
- // 9 10 11 12
- // 13 14 15 16
- // matrix[row, col] = row * n + col + 1;
- // swicth row and col and you'll get:
- // 1 5 9 13
- // 2 6 10 14
- // 3 7 11 15
- // 4 8 12 16
- matrix[col, row] = row * n + col + 1;
- // alternative way:
- // matrix[row, col] = row + col * n + 1;
- }
- }
- }
- public static void PrintMatrix(int[,] matrix)
- {
- for (int row = 0; row < matrix.GetLength(0); row++)
- {
- for (int col = 0; col < matrix.GetLength(1); col++)
- {
- Console.Write("{0,3}", matrix[row, col]);
- }
- Console.WriteLine();
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement