This is a program to check prime number in C.
Prime Number: A prime number is a number divisible only by 1 or itself.
Example: 2, 3, 5, 7, 11, 13, …., etc.
This program takes a number and checks whether a given number is prime or not.
1. Take a number as input.
2. Check if the number is divisible by any of the natural numbers starting from 2.
3. If it is, then it is not a prime number. Otherwise, it is a prime number.
4. Exit.
Here is the source code of the C program to check if a number is a prime number or not. The C program is successfully compiled and run on a Linux system. The program output is also shown below.
/*
* C Program to find prime numbers and
* Output the given number with a suitable message.
*/
#include <stdio.h>
#include <stdlib.h>
void main()
{
int num, j, flag;
printf("Enter a number \n");
scanf("%d", &num);
if (num <= 1)
{
printf("%d is not a prime numbers \n", num);
exit(1);
}
flag = 0;
// To check prime number
for (j = 2; j <= num / 2; j++)
{
if ((num % j) == 0)
{
flag = 1;
break;
}
}
if (flag == 0)
printf("%d is a prime number \n", num);
else
printf("%d is not a prime number \n", num);
}
1. Take a number as input and store it in the variable num.
2. If the number is lesser than or equal to 1, then print the output as ” It is not a prime number”.
3. Initialize the variable flag to zero.
4. Using for loop, check if the input number is divisible by any of the natural numbers starting from 2.
5. If it is, then assigns the variable flag with 1.
6. Print the output as “It is a prime number”, if the variable flag ==0.
7. Otherwise print the output as “It is not a prime number” and exit.
Enter a number 23 23 is a prime number Enter a number 15 15 is not a prime number
Sanfoundry Global Education & Learning Series – 1000 C Programs.
Here’s the list of Best Books in C Programming, Data-Structures and Algorithms
- Get Free Certificate of Merit in C Programming
- Participate in C Programming Certification Contest
- Become a Top Ranker in C Programming
- Take C Programming Tests
- Chapterwise Practice Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
- Chapterwise Mock Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
- Buy Computer Science Books
- Watch Advanced C Programming Videos
- Apply for Computer Science Internship
- Practice Computer Science MCQs
- Buy C Books