A prime number is a natural number that has only one and itself as factors.

__Example:__

2, 3, 5, 7, 11 and 13 are few prime numbers.

Above numbers can only be divided evenly by *1 or itself*, so these numbers are prime numbers.

### Prime Number Check Program in C

__Program:__

#include <stdio.h>

main() {

int n, i, c = 0;

printf("Enter any number n:");

scanf("%d", &n);

/*logic*/ for (i = 1; i <= n; i++) {

if (n % i == 0) {

c++;

}

}

if (c == 2) {

printf("n is a Prime number");

}

else {

printf("n is not a Prime number");

}

return 0;

}

__Program Output:__

Enter any number n: 7

n is Prime

__Explanation:__

consider a number *n=5*

*for(i=0;i<=n;i++)* /* for loop is executed until the n value equals i */

*i.e. for(i=0;i<=5;i++)* /* here the for loop is executed until i is equal to n */

1st iteration:* i = 1; i <= 5; i++*

here i is incremented i.e. i value for next iteration is 2

now if(n%i==0) then c is incremented

i.e.if(5%1==0)then c is incremented, here 5%1=0 thus c is incremented.

now c=1;

2nd iteration: *i = 2; i <= 5; i++*

here i is incremented i.e. i value for next iteration is 3

now if(n%i==0) then c is incremented

i.e.if(5%2==0) then c is incremented, but 5%2!=0 and so c is not incremented, c remains 1

c=1;

3rd iteration: *i = 3; i <= 5; i++*

here i is incremented i.e. i value for next iteration is 4

now if(n%i==0) then c is incremented

i.e.if(5%3==0) then c ic incremented, but 5%3!=0 and so c is not incremented, c remains 1

c=1;

4th iteration: *i = 4; i <= 5; i++*

here i is incremented i.e. i value for next iteration is 5

now if(n%i==0) then c is incremented

i.e. if(5%4==0) then c is incremented, but 5%4!=0 and so c is not incremented, c remains 1

c=1;

5th iteration: *i = 5; i <= 5; i++*

here i is incremented i.e. i value for next iteration is 6

now if(n%i==0) then c is incremented

i.e. if(5%5==0) then c is incremented, 5%5=0 and so c is incremented.

i.e. c=2

6th iteration: *i = 6; i <= 5; i++*

here i value is 6 and 6<=5 is false thus the condition fails and control leaves the for loop.

now if(c==2) then n is a prime number

we have c=2 from the 5th iteration and thus n=5 is a Prime number.

## No Comments