Create a 2-dimensional (3 x 3) integer array which contains 9 random numbers ranged from 0 to 100. For each number, determine whether the number is a prime number or not. You should define a method to test whether a number is prime or not. A prime number (n) meets the following requirements:
- n must be larger than 1.
- If n is greater than 1, then start dividing by 2, 3, …, n-1 and check the remainder. If none of remainder equals to 0, then n is a prime number. Otherwise, it is not.
Your programme should:
- Print all elements in 3 rows
- Print the total number of prime numbers.
- Print all location(s) of prime number(s) and their values (if there is any).
Sample Screen Output:
Row 1: 5 / 81 / 45
Row 2: 21 / 27 / 17
Row 3: 31 / 77 / 41
Total Number of Prime Number: 4
Row 1 and Column 1: 5
Row 2 and Column 3: 17
Row 3 and Column 1: 31
Row 3 and Column 3: 41
Hemant SrivastavaPosted Nov 18, 2012, 1:21 AM
I created a class PrimeNumChecker and main program is creating object of PrimeNumChecker class and calling its method to give desired output.
Here is the solution:
class PrimeNumChecker
{
int [,] matrix = new int [3,3];
Random rndm = new Random(0);
public void CreateMatrix ()
{
for (int i=0; i< 3; i++)
for (int j=0; j<3; j++)
{
matrix[i,j] = Convert.ToInt32(rndm.Next(100));
}
}
public void DisplayMatrix ()
{
Console.WriteLine ("Input Matrix is:\n");
for (int i=0; i< 3; i++)
{
Console.Write("ROW-"+(i+1)+ "\t");
for (int j=0; j<3; j++)
{
Console.Write (matrix [i, j] + "\t");
}
Console.WriteLine ();
}
}
public void ProcessMatrix ()
{
CountPrimeNumbers();
DisplayPrimeNumber();
}
private void CountPrimeNumbers ()
{
int primeNumCount =0;
for (int i=0; i< 3; i++)
{
for (int j=0; j<3; j++)
{
if(IsPrimeNumber(matrix [i, j]))
{
primeNumCount ++;
}
}
}
Console.WriteLine ("\nTotal number of prime numbers are: "+ primeNumCount);
}
private void DisplayPrimeNumber ()
{
for (int i=0; i< 3; i++)
{
for (int j=0; j<3; j++)
{
if(IsPrimeNumber(matrix [i, j]))
{
Console.WriteLine ("Row "+ (i+1) + " Column "+ (j+1) + ": " +matrix[i,j]);
}
}
}
}
private bool IsPrimeNumber(int num)
{
bool bPrime = true;
int factor = num / 2;
int i = 0;
for (i = 2; i <= factor; i++)
{
if ((num % i) == 0)
bPrime = false;
}
return bPrime;
}
}
class MainClass
{
public static void Main (string[] args)
{
PrimeNumChecker objPrimeChecker = new PrimeNumChecker();
objPrimeChecker.CreateMatrix();
objPrimeChecker.DisplayMatrix();
objPrimeChecker.ProcessMatrix();
Console.Read();
}
}
Output comes like:
Hemant SrivastavaPosted Nov 18, 2012, 1:23 AM
Thanks,
Hemant