Check for Prime Numbers using Loops in C

To check whether a number is prime in C, we use loops to test if it is divisible by any number other than 1 and itself. A prime number has exactly two divisors: 1 and itself. We can implement this check using for or while loops, iterating through possible divisors up to a certain limit.


Examples to Check Prime Numbers

1. Checking Prime Number Using a for Loop

In this example, we check if a given number is prime using a for loop. We iterate from 2 to num/2 and check if the number is divisible by any value. If it is, the number is not prime.

main.c

</>
Copy
#include <stdio.h>

int main() {
    int num, isPrime = 1;
    
    printf("Enter a number: ");
    scanf("%d", &num);
    
    if (num <= 1) {
        isPrime = 0;
    } else {
        for (int i = 2; i <= num / 2; i++) {
            if (num % i == 0) {
                isPrime = 0;
                break;
            }
        }
    }

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

    return 0;
}

Explanation:

  1. We declare num for input and isPrime initialized to 1 (true).
  2. We take user input using scanf().
  3. If num is less than or equal to 1, we mark it as not prime.
  4. We use a for loop to check divisibility from 2 to num/2.
  5. If we find a divisor, we set isPrime to 0 and break the loop.
  6. We print whether the number is prime based on isPrime‘s value.

Output:

Enter a number: 7
7 is a prime number.

2. Checking Prime Number Using a while Loop

In this example, we use a while loop instead of a for loop to check if a number is prime. We incrementally divide the number by values starting from 2.

main.c

</>
Copy
#include <stdio.h>

int main() {
    int num, i = 2, isPrime = 1;

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

    if (num <= 1) {
        isPrime = 0;
    } else {
        while (i <= num / 2) {
            if (num % i == 0) {
                isPrime = 0;
                break;
            }
            i++;
        }
    }

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

    return 0;
}

Explanation:

  1. We initialize i to 2 and isPrime to 1.
  2. We take user input using scanf().
  3. If num is ≤ 1, we mark it as not prime.
  4. The while loop runs from 2 to num/2.
  5. If num is divisible by any i, we set isPrime to 0 and break.
  6. Finally, we print whether the number is prime based on isPrime.

Output:

Enter a number: 12
12 is not a prime number.

Conclusion

We explored different methods to check if a number is prime in C:

  1. Using a for loop: Iterates through possible divisors up to num/2.
  2. Using a while loop: Achieves the same check but with a while condition.