We are providing online training of realtime Live project on Asp.Net MVC with Angular and Web API. For more information click here. If you have any query then drop the messase in CONTACT FORM

Saturday, June 13, 2015

Write a program of Magic Matrix in C#

class matrix
    {

        public void makeSquare(int n)
        {

            int[,] square = new int[n, n];
            int row, coll;

            for (row = 0; row < n; row++)
            {

                for (coll = 0; coll < n; coll++)
                {

                    square[row, coll] = 0;
                }
            }
            row = 0;
            coll = (int)(Math.Floor((double)n / 2));
            square[row, coll] = 1;
            int lastRow = 0, lastColl = 0;
            for (int i = 2; i <= Math.Pow(n, 2); i++)
            {
                row -= 1;
                if (row < 0) row = n - 1;
                coll -= 1;
                if (coll < 0) coll = n - 1;
                if (square[row, coll] == 0)
                {
                     square[row, coll] = i;
                    lastRow = row;
                    lastColl = coll;
                }
                else
                {
                    row = lastRow++;
                    coll = lastColl - 1;
                    square[row, coll] = i;
                    lastRow = row;
                    lastColl = coll;

                }
            }

            for (row = 0; row < n; row++)
            {
                for (coll = 0; coll < n; coll++)
                {

                    Console.Write(square[row, coll] + " ");
                }
                Console.WriteLine();
            }
            Console.Write("The Magical Sum is : ");
            int sum = 0;
            for (int i = 0; i < n; i++)
            {
                sum += square[0, i];
            }
            Console.Write(sum);
        }
    }


    class Program
    {
        static void Main(string[] args)
        {

            Console.Write("Enter An Odd Number : ");
            int n = Int32.Parse(Console.ReadLine());
            if (n < 3)
            {
                Console.WriteLine("Minimum Value allowed is 3.");
                Console.WriteLine("Your argument is invalid.");
            }
            else if (n % 2 == 0)
            {
                Console.WriteLine("Odd numbers only.");

                Console.WriteLine("Your argument is invalid.");
            }
            else
            {
                Console.WriteLine();
                Console.WriteLine(n + " x " + n + " Magic Square :");
                Console.WriteLine();
                matrix magic = new matrix();
                magic.makeSquare(n);
                Console.WriteLine();
            }
            Console.ReadLine();
        }
    } 
OUTPUT:

No comments: