Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //Write a program that fills and prints a matrix of size (n, n) as shown below: (examples for n = 4).
- using System;
- class FillsAndPrintsAMatrix
- {
- static void Main()
- {
- int n = int.Parse(Console.ReadLine());
- int[,] matrix;
- matrix=MatrixA(n);
- PrintMatrix(matrix);
- matrix = MatrixB(n);
- PrintMatrix(matrix);
- matrix = MatrixC(n);
- PrintMatrix(matrix);
- }
- static int[,]MatrixA(int n)
- {
- int[,] matrix = new int[n, n];
- for (int rows = 0; rows < matrix.GetLength(0); rows++)
- {
- int counter = rows;
- counter++;
- for (int col = 0; col < matrix.GetLength(1); col++, counter += n)
- {
- matrix[rows, col] = counter;
- }
- }
- return matrix;
- }
- static int[,]MatrixB(int n)
- {
- int[,] matrix = new int[n, n];
- for (int rows = 0; rows < matrix.GetLength(0); rows++)
- {
- int counter = rows;
- int counter2 = 0;
- counter++;
- for (int col = 0; col < matrix.GetLength(1); col++, counter += n)
- {
- if (col % 2 == 0)
- {
- matrix[rows, col] = counter;
- }
- else
- {
- counter2 = n * (col + 1);
- counter2 -= rows;
- matrix[rows, col] = counter2;
- }
- }
- }
- return matrix;
- }
- static int[,]MatrixC(int n)
- {
- int[,] matrix = new int[n, n];
- int counter = 1;
- for (int rows = matrix.GetLength(0) - 1; rows >= 0; rows--)
- {
- for (int col = 0; col < n - rows; col++)
- {
- matrix[(rows + col), col] = counter;
- counter++;
- }
- }
- for (int col = 1; col < matrix.GetLength(1); col++)
- {
- for (int rows = 0; rows < n - col; rows++)
- {
- matrix[rows, (rows + col)] = counter;
- counter++;
- }
- }
- return matrix;
- }
- static void PrintMatrix(int [,] matrix)
- {
- for (int rows = 0; rows < matrix.GetLength(0); rows++)
- {
- for (int col = 0; col < matrix.GetLength(1); col++)
- {
- Console.Write("{0,4}",matrix[rows,col]);
- }
- Console.WriteLine();
- }
- Console.WriteLine();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement