Archive for June, 2013

Write a Program to Print Following Number Pattern

Input  : Number of Rows

Output:

1
121
12321
1234321
123454321

Code

 

        public static void PrintNumberPattern2(int rows)
        {
            int i, j, k;
            //Loop for number of Rows
            for (i = 1; i <= rows; i++)
            {
                // Loop for printing numbers in increasing order
                for (j = 1; j < 2 * i + 1; j++)
                {
                    Console.Write(j);
                    if (j >= i)
                    {
                        break;
                    }
                }
                // Loop for printing numbers in decreasing order
                for (k = j - 1; k > 0; k--)
                {
                    Console.Write(k);
                }
                Console.WriteLine("");
            }
        }

Write a Program for Rotate a Sqaure Matrix by 90 Degree

Today we have to write a program for rotating a given matrix by 90 degree. This code only works with square matrix.

Code

        public static void MatrixRotation<T>(T[,] matrix)
        {
            Console.WriteLine("\n Input Matrix");
            Print2DMatrix(matrix);
            int row = matrix.GetLength(0);
            int column = matrix.GetLength(1);

            T temp;
            for (int i = 0; i < row; i++)
            {
                for (int j = i + 1; j < column; j++)
                {
                    temp = matrix[j, i];
                    matrix[j, i] = matrix[i, j];
                    matrix[i, j] = temp;
                }
            }


            for (int i = 0; i < row / 2; i++)
            {
                for (int j = 0; j < column; j++)
                {
                    temp = matrix[j, i];
                    matrix[j, i] = matrix[j, row - i - 1];
                    matrix[j, row - i - 1] = temp;
                }
            }
            Console.WriteLine("\n Rotation matrix");
            Print2DMatrix(matrix);

        }

        private static void Print2DMatrix<T>(T[,] matrix)
        {
            Console.WriteLine("--------------\n");
            int row = matrix.GetLength(0);
            int column = matrix.GetLength(1);

            for (int i = 0; i < row; i++)
            {
                for (int j = 0; j < column; j++)
                {
                    Console.Write(matrix[i, j] + " ");
                }
                Console.WriteLine(" ");
            }

        }

Result


Input Matrix

————–

11 12 13 14 15

21 22 23 24 25

31 32 33 34 35

41 42 43 44 45

51 52 53 54 55

Rotation matrix

————–

51 41 31 21 11

52 42 32 22 12

53 43 33 23 13

54 44 34 24 14

55 45 35 25 15

Input Matrix

————–

A B C D

E F G H

I J K L

M N O P

Rotation matrix

————–

M I E A

N J F B

O K G C

P L H D