Hi Friends
Now we are going to learn about print prime numbers upto n.
Sample input
20
Sample out put.
2 3 5 7
Program
You can also copy the program below
#include<stdio.h>
int main()
{
int n,i,j,count;
scanf("%d",&n);
for(i=0; i<=n; i++)
{
count=0;
for(j=0; j<i; j++)
{
if(i%j==0)
{
count++;
}
}
if(count==2)
{
printf("%d ",i);
}
}
}
Explination -
In this program we have to check the condition of prime number .
We know that a number is said to be a prime number when it has only two factors that are 1 and itself( ex- 5 has factors 1 and 5).
so we use nested loops to check all numbers from 2 to n .
In first loop we take numbers from 2 (becuase 1st prime number is 2) and increment the value upto n.
And in second loop we take numbers from 1 to i. Here we check the factors of i. If i%j==0 we increase the count value(initially we take count=0) . And if count ==2 means the number have two factors.
So we print (i) that is the prime number.