check if the number is prime in c

To check if a number is prime in C, you can follow these steps:

  1. Get the input number from the user - Prompt the user to enter a number to check if it is prime.

  2. Check for special cases - Handle special cases where the input number is less than or equal to 1. In these cases, the number is not prime. You can return false or display a message indicating that the number is not prime.

  3. Iterate through potential divisors - Start a loop from 2 to the square root of the input number. For each iteration, check if the input number is divisible by the current divisor. If it is, the number is not prime. You can return false or display a message indicating that the number is not prime.

  4. Return true if the number is prime - If the loop completes without finding any divisors, the number is prime. You can return true or display a message indicating that the number is prime.

Here's an example implementation of the above steps in C:

#include <stdio.h>
#include <math.h>

int isPrime(int num) {
    // Check for special cases
    if (num <= 1) {
        return 0; // Not prime
    }

    // Iterate through potential divisors
    for (int i = 2; i <= sqrt(num); i++) {
        if (num % i == 0) {
            return 0; // Not prime
        }
    }

    return 1; // Prime
}

int main() {
    int num;
    printf("Enter a number: ");
    scanf("%d", &num);

    if (isPrime(num)) {
        printf("%d is prime.\n", num);
    } else {
        printf("%d is not prime.\n", num);
    }

    return 0;
}

Explanation of the steps:

  1. The user is prompted to enter a number using printf and scanf.

  2. The function isPrime is defined to check if a number is prime. It takes an integer num as input.

  3. The special cases are handled using an if statement. If the number is less than or equal to 1, the function returns 0, indicating that the number is not prime.

  4. A for loop is used to iterate through potential divisors from 2 to the square root of the input number. The loop variable i represents the current divisor.

  5. Inside the loop, the input number is checked for divisibility by the current divisor using the modulo operator %. If the input number is divisible by i, the function returns 0, indicating that the number is not prime.

  6. If the loop completes without finding any divisors, the function returns 1, indicating that the number is prime.

  7. In the main function, the user's input is passed to the isPrime function. Depending on the return value, a message is displayed indicating whether the number is prime or not.

That's it! The code checks if a number is prime in C.