**Prime number program in C **is the one of the most important program in c.

Prime number program in C is mostly asked in the exams, interviews etc.In this tutorial we simply checking that number is prime number.

**What is prime number?**

Any number which is divisible only by one and itself. two (2) is smallest even prime number.

for example prime numbers are : 2, 3, 5, 7, 11, 13, 17,…..

A number greater than one can be factorized into prime numbers, for example, 540 = 2^{2}*3^{3}*5^{1}.

**Logic to Check number is prime number :**

We take a number input from user. next we check whether number is divisible by 1 and itself only if this is true then print number is prime number.

**Algorithm for prime numbers in c:**

- start
- Declare variables.
- Take a number user input
- Check prime number with divisibility condition.
- if condition true then print number prime number else not
- End

## Program for prime number in c

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
#include<stdio.h> main() { int n, c = 2; printf("Enter a number to check if it is prime\n"); scanf("%d",&n); for ( c = 2 ; c <= n - 1 ; c++ ) { if ( n%c == 0 ) { printf("%d isn't prime.\n", n); break; } } if ( c == n ) printf("%d is prime.\n", n); return 0; } |

**Output :**

**Explanation :**

**First include preprocessor directives stdio.h in program.****Next write main function from where the execution of the program begins.****Declare the variables int n, c = 2. n => to store the number from user and c=2 => is to check prime number from 2.****Take a input number from user and store it in n variable.****Next statements for ( c = 2 ; c <= n – 1 ; c++ )**this statement is to check number from 2 to N divides the number user entered.(starts from 2 as 2 is the smallest even prime number)- We know that number is prime number if it divisible by one and itself. so based on that we write the condition
**if ( n%c == 0 )**if this condition becomes true then the number is divided by another number which breaks the rule of prime number rule. So we consider that number is not prime number so we print**printf(“%d isn’t prime.\n”, n) and break execution of loop.** - if number is not divided by other numbers from 2 to N then that number is prime number. so at end we print printf(“%d is prime.\n”, n).

## Leave a Reply