Check Whether a Number is Prime or Not in C

Exercise:

Write a C Program to check whether a number is prime or not.

Click Here to View the Solution!
#include <stdio.h>
int main() {
    int num, i, flag = 0;
    printf("Enter a positive integer: ");
    scanf("%d", &num);
    for (i = 2; i <= num / 2; ++i) {
        // condition for non-prime
        if (num % i == 0) {
            flag = 1;
            break;
        }
    }
    if (num == 1) {
        printf("1 is neither prime nor composite.");
    }
    else {
        if (flag == 0)
            printf("%d is a prime number.", num);
        else
            printf("%d is not a prime number.", num);
    }
  return 0;
}
Click Here to View the Output!
Enter a positive integer: 6 
6 is not a prime number.
Click Here to View the Explanation!
  • This program is used to check whether a number is a prime number or not.
  • In main(), the program requests the user to enter a positive integer and stores it into the variable num using the scanf() function.
  • A variable flag is initialized as flag = 0.
  • A for loop is used that will iterate between i = 2 and i <= num/2.
  • Inside the loop, the condition for a non-prime number is checked in the first if statement. It will check whether num is exactly divisible by i, if true, flag will become 1 and the loop will end.
  • After the loop, in the if…else statement, if num will be equal to 1, num will be considered neither a prime nor a composite number.
  • Else, if the flag will remain 0, then num will be a prime number otherwise, num will be a non-prime number and flag will be equal to 1.
  • The return 0 statement is used to exit the program execution.