Write a program in C# Sharp to accept a matrix and determine whether it is a sparse matrix

  • برمجة سي شارب
  • برمجة

Write a program in C# Sharp to accept a matrix and determine whether it is a sparse matrix.
Test Data :
Input the number of rows of the matrix : 2
Input the number of columns of the matrix : 2
Input elements in the first matrix :
element - [0],[0] : 0
element - [0],[1] : 0
element - [1],[0] : 1
element - [1],[1] : 0
Expected Output :
The given matrix is sparse matrix.
There are 3 number of zeros in the matrix

الأجوبة

/*A sparse martix is matrix which  has more zero elements than nonzero elements */
using System;  
public class Exercise29  
{  
    public static void Main()
{
      	int[,] arr1 = new int[10,10];
	    int i,j,r,c;
	    int ctr=0;	
     Console.Write("\n\nDetermine whether a matrix is a sparse matrix :\n ");
     Console.Write("----------------------------------------------------\n");	
     Console.Write("Input the number of rows of the matrix : ");
	 r = Convert.ToInt32(Console.ReadLine());
     Console.Write("Input the number of columns of the matrix : ");
	 c = Convert.ToInt32(Console.ReadLine());
	 Console.Write("Input elements in the first matrix :\n");
       for(i=0;i<r;i++)
        {
            for(j=0;j<c;j++)
            {
	           Console.Write("element - [{0}],[{1}] : ",i,j);
			   arr1[i,j] = Convert.ToInt32(Console.ReadLine());
			if (arr1[i,j]==0)
			{
				++ctr;
			}
            }
        }  
	if (ctr>((r*c)/2))
	{
		Console.Write ("The given matrix is sparse matrix. \n");
	}
	else
		Console.Write ("The given matrix is not a sparse matrix.\n");

	Console.Write ("There are {0} number of zeros in the matrix.\n\n",ctr);	
	}
}
هل كان المحتوى مفيد؟

تبحث عن مدرس اونلاين؟

محتاج مساعدة باختيار المدرس الافضل؟ تواصل مع فريقنا الان لمساعدتك بتأمين افضل مدرس
ماهو التخصص الذي تبحث عنه؟
اكتب هنا...