Select prime numbers from the given array

Here is an example that demonstrates how to select prime numbers from the given array

Code :

//Assign values to an array
int[] nums = { 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13};
Console.WriteLine("*********Pick prime numbers from the given array *********************\n");

int j;
//Iterate through the items of array
for (int i = 0; i < nums.Length; i++)
{

// see if num is evenly divisible
for ( j = 2; j < nums[i]; j++)
if((nums[i]%j ==0))
{
// num is evenly divisible -- not prime
Console.WriteLine("{0} : Is NOT a primenumber", + nums[i]);
break;
}
if (j== nums[i])
{
Console.WriteLine("{0} : Is a primenumber", +nums[i]);

}

}


Output:

*********Pick prime numbers from the given array *********************

2 : Is a primenumber
3 : Is a primenumber
4 : Is NOT a primenumber
5 : Is a primenumber
6 : Is NOT a primenumber
7 : Is a primenumber
8 : Is NOT a primenumber
9 : Is NOT a primenumber
10 : Is NOT a primenumber
11 : Is a primenumber
12 : Is NOT a primenumber
13 : Is a primenumber

 
 
 
 
Ebook Download
View all
Learn
View all