# Prime Number Program in C

Spread the love
•
•
•
•
•
•
•
•
•
•

Prime Number Program in C: Prime numbers are number that should be divided by itself or by “1” only and should be greater than “1”.

2, 3, 5, 7, 11 etc. are considered as prime numbers as they are divisible by them self and by “1” only.

### Prime Number Program in C Algorithm: Prime Number Program in C

logic for prime number in c

### Prime number program in c using for loop:

Example:

``````#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int number,a,b=0,flag=0;
printf("Please enter the number that you have to check prime or not");
scanf("%d",&number);
b=number/2;
for(a=2;a<=b;a++)
{
if(number%a==0)
{
printf("%d is not a prime number", number);
flag=1;
break;
}
}
if(flag==0)
printf("%d is a prime number",number);
getch();
}``````

Output:

``````Please enter the number that you have to check prime or not 3
3 is a prime number

Please enter the number that you have to check prime or not 4
4 is not a prime number``````

In order to understand how the for loop works then check for loop in c with examples

### Prime number program in C using while loop:

To check whether the given number is a prime number or not, present we are using while loop and iterate from 2 to half of the given number.

If any number is divisible other than itself or “1” then we can exit from the while loop in C.

Here is the example of while loop.

In this example we have taken num, a, b, c as variables.

Variables b, c are initialized to “0” and a as “2”.

If num % a==0 then the given number is not prime and the program terminates from the loop.

Example of Prime Number Program in C using While loop:

``````#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int num,a,b=0,c=0;
printf("Please enter the number that you have to check prime or not");
scanf("%d",&num);

b=num/2;
a=2;

while(a<=b)
{
if(num%a==0)
{
printf("%d is not a prime number",num);
c=1;
break;
}
a++;
}
if(c==0)
printf("%d is a prime number",num);
getch();
}``````

Output:

``````Please enter the number that you have to check prime or not 5
5 is a prime number

Please enter the number that you have to check prime or not 10
10 is not a prime number``````

Using C

Spread the love
•
•
•
•
•
•
•
•
•
•
Scroll to Top