In this C programming example, we will learn about the Prime Number program in C. We specifically write a program to check the entered number is prime or not.
Prime Number:
A Prime Number is a number that is only divisible by 1 and itself. Example: 2, 3, 5, 7, 11, 13, 17, etc. These numbers are only divisible by 1 and the number itself.
Note:
0 and 1 is not a prime number and 2 is the only even and smallest prime number.
- C Program to Print Prime Numbers up to a Given Number
- C program to Print Prime Numbers in a Given Range (max & min)
You must know the following topics in C first:
C Program to Check Whether a Given Number is Prime or Not
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 35 36 | #include <stdio.h> int main() { int num, i, flag = 0; //user input printf("Enter the number: "); scanf("%d", &num); for (i = 2; i <= num / 2; ++i) { // checking for non-prime if (num % i == 0) { flag = 1; break; } } //checkinh for the entered number is 1 or not //because 1 cannot be a prime number if (num == 1) { printf("1 is not a prime number."); } else { if (flag == 0) printf("%d is a prime number.", num); else printf("%d is not a prime number.", num); } return 0; } |
Output:
//Run 1
Enter the number: 13
13 is a prime number.
//Run2
Enter the number: 1
1 is not a prime number.
You may go through the following C program on the prime number.
- C Program to Print Prime Numbers up to a Given Number
- C program to Print Prime Numbers in a Given Range (max & min)