Q:

# C Program to Check if a given Number is Prime or not

belongs to collection: C programs - Basic C Programs

This C programming example is to check whether an entered number is prime or not. A prime number is a positive integer which is divisible only by 1 and itself. For example, 3,5,7,11,17 are few prime numbers. This program check for the prime number using the modulus(%) operator.

need an explanation for this answer? contact us directly to get an explanation for this answer

C Program to Check if a given Number is Prime or not - Source code

``````#include <stdio.h>

int main()
{
int n, i, flag;

printf("Enter a number \n");
scanf("%d", &n);

if (n <= 1)
{
printf("Please enter a positive number.", n);
return 0;
}
flag = 0;
for (i = 2; i <= n / 2; i++)
{
if ((n % i) == 0)
{
flag = 1;
break;
}
}
if (flag == 0)
{
printf("%d is a prime number \n", n);
}

else
{
printf("%d is not a prime number \n", n);
}

return 0;
}``````

Program Output

```Case 1:

Enter a number
451
451 is not a prime number

Case 2:

Enter a number
79
79 is a prime number

Case 3:

Enter a number
-12
Please enter a positive number.```

Program Explanation

1. The program accept a positive integer using the scanf function. If the number entered by the user is negative, it prompt the user to enter a positive number.

2. To check for the prime number, modulus operator is used which returns the remainder after dividing the entered number with each number up to n/2 (starting from 2).

3. If the remainder comes out zero in any case, that means the number is not prime and the variable flag is set to 1 and for loop is existed. Otherwise the value of flag remains 0.

4. Depending on the value of variable flag, message is printed on the screen using if-else statement.

need an explanation for this answer? contact us directly to get an explanation for this answer