The following program will print prime numbers in an array.
C++ Program to Find Prime Numbers in an Array:
Prime numbers are those which are divisible by themselves and 1. So, when we have to check that a number is a prime number or not, we have to find out that if it is divisible by any other number other than itself and 1. Also, A number can be divided by a value equal to half of the number. So, if 'n' be a number, then the possible divisors will be less than and equal to the value of n/2.
Source Code:
#include <iostream>
using namespace std;
int main()
{
// initializing an array of 20 spaces.
int sizeOfArray = 20;
int arr[sizeOfArray];
for (int i = 0, count = 1; i < sizeOfArray; i++, count++)
{
arr[i] = count;
}
cout << "Original Array: ";
for (int i = 0; i < sizeOfArray; i++)
{
cout << arr[i] << " ";
}
cout << endl;
// printing prime number:
cout << endl;
cout << "Prime Numbers In Array:";
bool primeNumberFound = false; // for checking that array has any prime element or not.
bool isPrimeNumber = true; // for checking the current number unber observation.
for (int i = 0; i < sizeOfArray; i++)
{
if (arr[i] == 1)
{
continue;
}
for (int j = 2; j <= (arr[i] / 2); j++)
{
isPrimeNumber = true;
if ((arr[i] % j) == 0)
{
isPrimeNumber = false;
break;
}
}
if (isPrimeNumber == true)
{
cout << arr[i] << " ";
primeNumberFound = true;
}
}
if (primeNumberFound == false)
{
cout << "There are no prime numbers in the Array.";
}
cout << endl;
return 0;
}
Output:
Original Array: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
Prime Numbers In Array:2 3 5 7 11 13 17 19
If you have any queries about this program or about anything, do ask in a comment. I will try to answer as many questions as I can.
Comments
Post a Comment