## Prime Number In C Programming

This is a program of Prime Number, First we will print prime number till N number. Second, we will check the number you entered is a prime number or not.

**Explanation:**

First, we take a number from the user.

Then a loop i starts from 2 (as we know 0 and 1 are not prime number) and it proceeds till N number.

Inside that loop, there is another loop j which starts with 2 and proceeds till i number. In that loop, it will compare that i mod of j == 0 that means i number is divisible by j number if it is divisible then break the statement.

We have used flag variable before second loop starts the flag is initialised to zero and if i%j==0 then flag value changes to one; that means if the number is divisible by j, number is not prime; so the flag value initialised to 1.

If i%j is not equal to 0 that means it is a prime number. So, we took ‘if’ condition after second loop that compares if flag value is equal to 0 then it is a prime number.

**code:**

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 |
#include <stdio.h> #include <conio.h> void main() { int n,i,j,flag; printf("Prime number from 1 to : "); scanf("%d",&n); for(i=2;i<=n;i++) { flag=0; for(j=2;j<i;j++) { if(i%j==0) { flag=1; break; } } if (flag==0) { printf("\n%d",i); } } getch(); } |

**Output:**

Prime number from 1 to : 19

2

3

5

7

11

13

17

19

#2 Check whether given number is prime or not.

**Explanation:**

A number is taken from user. We want to check whether it is prime or not. It has a same logic. Just only one loop is used as we already know which number we should check.

**code:**

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 |
#include <stdio.h> #include <conio.h> void main() { int n,i,flag; printf("Enter the number:"); scanf("%d",&n); for(i=2;i<n;i++) { flag=1; if(n%i==0) { flag=0; break; } } if(flag!=0) { printf("The number is prime"); } else { printf("The number is not prime"); } getch(); } |

**Output:**

Enter the number:9

The number is not prime