Write a C program to print prime numbers from 1 to n

We already write a C program to check a number is prime or not. You can check that program code by clicking below link. So, let’s write a C program to print prime numbers from 1 to n.

Write a C program for prime number check [So Easy]

C program to print prime numbers from 1 to n

#include<stdio.h>
#include<conio.h>

void main()
{
int n,i,flag,j;
clrscr();
printf("Enter last range in n: ");
scanf("%d",&n);

printf("All prime numbers from 1 to %d\n",n);
for(i=1;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);
}
}
getch();
}

Output

Enter last range in n: 20
All prime numbers from 1 to 20
3
5
7
11
13
17
19

Program Code Explanation (PCE)

In this C program (to print prime numbers from 1 to n) we use two for loops. Outer for loop is used as a counter from 1 to ‘n’ number. And inner for loop is used to check each number for prime number. We use ‘flag’ variable as a checking variable.

C program to print prime numbers from 1 to n

Other programs codes

Hope that you understand the above program code. Please comment your questions or queries in below comment section. You can read our tech blog zerootech.com

Leave a Comment

error: Don\'t make piracy - Write your own content :)