Random matrix generation in C#

using System;

using System.Collections.Generic;

using System.Text;

using System.IO;

 

namespace ConsoleApplication1

{

    class Program

    {

        static void Main(string[] args)

        {

            //Code to generate a random matrix of given order

            Console.Write("Enter order of the matrix: ");

            int order = int.Parse(Console.ReadLine());

            Console.Write("Enter lower bound: ");

            int lowerBound = int.Parse(Console.ReadLine());

            Console.Write("Enter upper bound: ");

            int upperBound = int.Parse(Console.ReadLine());

            int[,] matrix = GenerateMatrix(order, lowerBound, upperBound);

            DisplayMatrix(matrix);   

        }

        public static int[,] GenerateMatrix(int order, int lowerBound, int upperBound)

        {

            int[,] matrix = new int[order, order];

            Random rand = new Random();

            for (int i = 0; i < order; i++)

            {

                for (int j = 0; j < order; j++)

                {

                    matrix[i, j] = rand.Next(lowerBound, upperBound+1);

                }

            }

            return matrix;

        }

        public static void DisplayMatrix(int[,] matrix)

        {

            Console.WriteLine("Displaying Matrix:");

            Console.WriteLine("==================");

            for (int i = 0; i < matrix.GetLength(0); i++)

            {

                for (int j = 0; j < matrix.GetLength(1); j++)

                {

                    Console.Write(matrix[i, j] + " ");

                }

                Console.WriteLine();

            }

            Console.WriteLine("==================");

        }

    }

}

 

Output:
=============================
Enter order of the matrix: 6
Enter lower bound: 0
Enter upper bound: 1
Displaying Matrix:
==================
0 0 1 1 0 1
1 0 0 0 0 1
0 0 0 0 1 1
1 1 0 1 0 0
1 1 0 1 1 0
0 0 1 0 0 1
==================
Press any key to continue . . .

Advertisements
This entry was posted in Information Technology. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s