Answer to Question #155862 in C++ for zain ul abdeen

Question #155862

Write a program that assigns Twenty random numbers to an array and counts all prime numbers entered by the user. The program finally displays a total number of primes in the array.


1
Expert's answer
2021-01-17T08:08:13-0500
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
bool checkPrimeNumber(int n) {
    bool isPrime = true;
    // 0 and 1 are not prime numbers
    if (n == 0 || n == 1) {
        isPrime = false;
    }
    else {
        for (int i = 2; i <= n / 2; ++i) {
            if (n % i == 0) {
                isPrime = false;
                break;
            }
        }
    }
    return isPrime;
}
int main () {
    srand(time(0));
    int n;
    int Arr[n];
    cout << "Enter the number of elements in array [the number must be greater than 20]: ";
    cin >> n;
    if (n > 20) {
        for (int i = 0; i < n; i++) {
            if (i < 20) {
                Arr[i] = rand() % 100;
            }
            else {
                int element;
                cout << "Enter elements: ";
                cin >> element;
                Arr[i] = element;
            }
        }
    }
    int count = 0, primeNumbers[100];
    cout << "The shown of array: \n";
    for (int i = 0; i < n; i++) {
        cout << Arr[i] << " ";
        if (checkPrimeNumber(Arr[i])) {
            primeNumbers[count++] = Arr[i];
        }
    }
    cout << "\nThe number of prime numbers: " << count << "\nthey are: ";
    for (int i = 0; i < count; i++) {
        cout << primeNumbers[i] << " ";
    }
    return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
APPROVED BY CLIENTS