Friday 4 July 2014

C# array exercise: matrix

In this C# exercise, you are about to write C# program to display a matrix as shown below. The diagonal of the matrix fills with 0s. The lower side fills will -1s and the upper side fills with 1s.

0
1
1
1
1

-1
0
1
1
1
-1
-1
0
1
1
-1
-1
-1
0
1
-1
-1
-1
-1
0

Solution:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

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

            printMatrix();
            Console.ReadLine();

        }


        public static void printMatrix()
        {

            int[,] matrix = new int[5, 5];
            int i, j;
            for (i = 0; i < 5; i++) //assign values to the matrix
                for (j = 0; j < 5; j++)
                { //if row=column=> fill the matrix with 0
                    if (i == j) matrix[i, j] = 0;//if row>columns=> fill matrix with -1
                    else if (i > j) matrix[i, j] = -1;//if row<columns=> fill matrix with 1
                    else matrix[i, j] = 1;
                }

            for (i = 0; i < 5; i++)
            { //print the matrix
                for (j = 0; j < 5; j++)
                    Console.Write("{0}\t", matrix[i, j]);
                Console.WriteLine();
            }

        }
  }
}


No comments:

Post a Comment