check prime cpp gfg

The C++ code below checks whether a given number is prime or not. Each step is explained to provide a better understanding of the code:

#include <iostream>
using namespace std;

bool isPrime(int n) {
    if (n <= 1) {
        return false;
    }

    for (int i = 2; i * i <= n; i++) {
        if (n % i == 0) {
            return false;
        }
    }

    return true;
}

int main() {
    int num;
    cout << "Enter a number: ";
    cin >> num;

    if (isPrime(num)) {
        cout << num << " is a prime number." << endl;
    } else {
        cout << num << " is not a prime number." << endl;
    }

    return 0;
}

Explanation:

  1. The code starts by including the iostream library, which is necessary for input and output operations.

  2. The using namespace std; line is used to avoid writing std:: before standard library functions.

  3. The isPrime function takes an integer n as input and returns a boolean value indicating whether n is prime or not.

  4. The first condition in the isPrime function checks if n is less than or equal to 1. If it is, the function returns false because prime numbers are greater than 1.

  5. The for loop in the isPrime function iterates from i = 2 to i * i <= n. This loop is used to check if n is divisible by any number between 2 and the square root of n. If n is divisible by any number in this range, it means n is not prime, and the function returns false.

  6. If the for loop completes without finding any divisors for n, it means n is prime, and the function returns true.

  7. The main function is where the program execution starts.

  8. Inside the main function, an integer variable num is declared to store the user input.

  9. The cout statement is used to display the message "Enter a number: " to prompt the user to enter a number.

  10. The cin statement is used to read the user input and store it in the num variable.

  11. The if statement checks if num is prime by calling the isPrime function. If it returns true, the message "num is a prime number." is displayed. Otherwise, the message "num is not a prime number." is displayed.

  12. Finally, the return 0; statement indicates that the program has executed successfully and returns the value 0 to the operating system.