Posted By:
23 Jun, 2013 1:13 pm PDT

Printing prime numbers in C

How can you print prime numbers in C programming?
Attachment:None


A number is prime if it is divisible only by one and itself. So to display n number of prime numbers we use the following logic:

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++;

}

 

Please see the video for more details

Was it useful?  



Here is the program that is also used for printing prime numbers 

 

#include<stdio.h>
void main()
{
int num,i=1,j,count;

printf("Enter Num value To Print Prime Numbers between 1 and Num: ");

scanf("%d",&num);
printf("Prime Numbers upto %d :\n \n",num);

while(i<=num)
{
count=0;
for(j=1;j<=i;j++)
{
if(i%j==0) //checking whether num is dvisible by j
count++;
}
if(count==2)  //if num is divisible by 2 numbers,then it is prime
printf("%d ",i);
i++;
}
printf("\n\n");

//getch(); 
}


Was it useful?  




Please login to reply to this problem.