**Print prime numbers till N program in C** is the one of the most important program in c.

Print prime numbers till N 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 print number till N :**

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.

**Concept you need to know from c :**

**Algorithm for prime numbers in c:**

- start
- Declare variables.
- Take N number user input
- Start for loop star from 2 to N
- Check prime number with divisibility condition.
- if condition true then print number
- else skip
- End

## Program for prime number till N in c

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 32 |
#include<stdio.h> int main() { int n, i = 3, count, c; printf("Enter the number of prime numbers required\n"); scanf("%d",&n); if ( n >= 1 ) { printf("First %d prime numbers are :\n",n); printf("2\n"); } for ( count = 2 ; count <= n ; ) { for ( c = 2 ; c <= i - 1 ; c++ ) { if ( i%c == 0 ) break; } if ( c == i ) { printf("%d\n", i); count++; } i++; } 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.****Print first prime number as we know its 2. printf(“2\n”);****Next statements for ( count = 2 ; count <= n ; )**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)for ( c = 2 ; c <= n – 1 ; c++ ) { if ( n%c == 0 ) { printf(“%d isn’t prime.\n”, n); break; } }- We know that number is prime number if it divisible by one and itself. so based on that we write the condition if ( c == i ) if this condition becomes true then the number is not divided by another number . So we consider that number is prime number so we print
**printf(“%d t prime.\n”, n)** - 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).
- At end we got all prime numbers printed on screen.

## Leave a Reply