Answer to Question #226616 in C++ for Kvngdanzy

Question #226616
A one dimensional array of 5 elements that accepts input from the keyboard and test for prime and input it into the 3rd index of the array
1
Expert's answer
2021-08-16T14:49:48-0400
#include <iostream>

using namespace std;

bool is_prime(int num) {
    if (num < 2) return false;
    if (num == 2) return true;
    if (num % 2 == 0) return false;
    for (int i = 3; (i * i) <= num; i += 2) {
        if (num % i == 0) return false;
    }
    return true;
}

int main() {
    int array[5];
    int num;
    cin >> num;
    if (is_prime(num)) {
        array[2] = num;
    }

    return 0;
}


To check that a number is prime, we just need to make sure that it is not divisible by any number from 3 to the square root of this number itself and is not a two.

And we insert it into the element with the number 2 because this is the third element in the array, since they are numbered from 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