C Program to generate prime numbers from 1 to N
Prime number is a number that is divided by 1 and itself. Prime numbers are greater than 1.
Examples: 2, 3, 5, 7, 11, 13, 17 ….
Let us write a C program to generate first N prime numbers using for loop. Here we are using nested for loops. Outer for loop is used to get the next number to be checked. Inner for loop is used to check whether the given number is prime or not.
Description:
n – input number, till which prime numbers are to be printed.
i and j – loop variables.
i – Outer for loop.
j – Inner for loop
flag – indicator : its value changes when number is divided by 2.
flag = 0 (initial value) – number is prime.
flag = 1 – number is not a prime.
Algorithm to print first N prime numbers:
STEP 1: START
STEP 2: READ a number greater than 1 till which you want to print prime number
READ n
STEP 3: REPEAT STEP 4 to STEP 6
LOOP from i=2 to n (Outer for loop)
STEP 4: SET the value of flag
flag = 0
STEP 5: LOOP from j=2 to (i/2) (Inner for loop)
if (i mod j) IS EQUAL TO zero
CHANGE the value of flag to 1
SET flag = 1
EXIT inner for loop
STEP 6: CHECK the value of flag
If flag = 0
PRINT “Print the value of i”
STEP 7: END
C Program to print prime numbers from 1 to N:
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,n,flag;
printf("Enter a number till which you want prime numbers: ");
scanf("%d",&n);
printf("Prime numbers are:\n");
for(i=2;i<=n;i++)
{
flag=0;
for(j=2;j<=i/2;j++)
{
if(i%j==0)
{
flag=1;
break;
}
}
if(flag==0)
{
printf("%d ",i);
}
}
}
Output 1:
Enter a number till which you want prime numbers: 13
Prime numbers are:
2 3 5 7 11 13
Output 2:
Enter a number till which you want prime numbers: 4
Prime numbers are:
2 3
Additional information:
Remember Zero (0) and 1 are not considered as prime numbers.
Two (2) is the only even prime number because all the even numbers are divided by 2.
C Program to print prime numbers from 1 to N using function isprime().
#include<stdio.h>
#include<conio.h>
void isprime(int n)
{
int i,j,flag;
for(i=2;i<=n;i++)
{
flag=0;
for(j=2;j<=i/2;j++)
{
if(i%j==0)
{
flag=1;
break;
}
}
if(flag==0)
printf("%d\n",i);
}
}
int main(){
int n;
printf("Enter a number greater than 1: ");
scanf("%d",&n);
printf("Prime numbers up to %d are:\n",n);
isprime(n);
getch();
return 0;
}
Output:
Enter a number greater than 1: 11
Prime numbers up to 11 are:
2
3
5
7
11
Example: C Program to generate first N prime numbers using function isprime().
#include<stdio.h>
#include<conio.h>
void isprime(int n)
{
int i=3,j,count,flag;
if(n>=1)
printf("2\n");
for(count=2;count<=n;)
{
flag=0;
for(j=2;j<=i/2;j++)
{
if(i%j==0)
{
flag=1;
break;
}
}
if(flag==0)
{
printf("%d\n",i);
count++;
}
i++;
}
}
int main(){
int n;
printf("Enter number of prime numbers you want: ");
scanf("%d",&n);
printf("First %d prime numbers are:\n",n);
isprime(n);
getch();
return 0;
}
Output:
Enter number of prime numbers you want: 7
First 7 prime numbers are:
2
3
5
7
11
13
17