Hey there!

Welcome to *ClearUrDoubt.com*.

In this post, we will look at a C program to find whether a given number is a prime number or not.

Prime Number: A number, which is divisible by only 1 and itself.

Eg.

1, 2, 3, 5, 7, 11 and so on are prime numbers.

To find whether a number(let’s say “num”) is prime or not, we need to check the remainder when we divide the given number with numbers from 2 to num/2.

This can be achieved using Modulus operator(“%”) in C. This operator gives the remainder of the division expression.

Eg.

10 % 3 = 1

11 % 3 = 2

12 % 3 = 0

Here is the C program:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
/* C program to find if the given number is a prime number */ #include<stdio.h> int main() { int num, i; int isPrime = 1; printf("Enter a number: "); scanf("%d", &num); for(i = 2; i <= num/2; i++) { if(num % i == 0) { isPrime = 0; break; } } if(isPrime == 1) { printf("%d is a prime number.", num); } else { printf("%d is not a prime number.", num); } return 0; } |

Output:

Happy Learning! 🙂

Please leave a reply in case of any queries.