# Prime Number Program in C

## C Program to Print Prime Number

A Prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. It is only divisible by 1 and itself, and it start from 2. The smallest prime number is 2.

## Prime number program in C

#include<stdio.h>
#include<conio.h>

void main()
{
int i,no;
clrscr();
printf("Enter any num: ");
scanf("%d",&no);
if(no==1)
{
printf("Smallest Prime no. is 2");
}
for(i=2;i<no;i++)
{
if(no%i==0)
{
printf("Not Prime no.");
break;
}
}
if(no==i)
{
printf("Prime no.");
}
getch();
}

## Output

Enter any num: 10
Not Prime no.

### Program Explanation

First enter any number if this that is 1 then show message "Smallest Prime no. is 2".

## Code

for(i=2;i<no;i++)
{
if(no%i==0)
{
printf("Not Prime no.");
break;
}
}

In above code we first perform for loop. First initialize i=2, because Every number is divisible by 1 so we start dividing given number from 2, then check condition "i" is less than number (i< no), and increment value of i (i++). Here "if(no%i==0)" is perform like : no%2==0, no%30=0, no%4==0, no%5==0, no%6==0, no%7==0,....... because every time value of i is increment until value of i is less than given number. If reminder is zero then print "Not Prime number" and control goes outside from for loop due to break keyword.

Note: break is only used within loops (for, while, etc) and switch case.

## Print next prime number in C

When we enter any number this code will print next Prime number.
Example: Suppose we enter 5 then next prime number is 7.

## C program to print next prime number

#include<stdio.h>
#include<conio.h>

void main()
{
int i,j=2,num;
clrscr();
printf("Enter any no.: ");
scanf("%d",&num);
printf("Next Prime no.: ");
for(i=num+1; i<3000; i++)
{
for(j=2; j<i; j++)
{
if(i%j==0)
{
break;
} // if
} // for
if(i==j || i==1)
{
printf("%d\t",i);
break;
} // if
}  // outer for
getch();
}

## Output

Enter any no.: 10
Next Prime no. 11