Tuesday 24 May 2016

Prime numbers #2 : C program .

Program #2 : 

Print the first n prime numbers, where n is entered by user .

Hi there !

Now we already know the logic of printing prime numbers .
Here what we wanna do is printing FIRST n prime numbers and not prime numbers up to n. So simply following that logic but in a little different way, we can achieve this.
Here we will introduce a counter variable , which will continue the process of printing prime number until it prints n prime numbers.
As we need to stop the procedure when the required numbers of prime numbers are printed , we must use EXIT control loop here . i.e. do{}while();
Try to develop program by yourself or copy the code given below !


C program : Prime numbers !



#include < stdio.h > 
int main()
{   int i,j,n;/*program to print first n prime numbers*/
    int count=0;/*variable for counting must be initiated*/
    printf("Enter n for printing first n prime numbers:\n");
    scanf("%d",&n);
    printf("First %d prime numbers are\n",n);
    i=2;/*consideration of numbers from 2 to nth prime number starts*/
    do{
            for(j=2;j < = i;j++)/*checking divisibility*/
                {
                    if(i%j==0)
                    {
                        break;
                    }
                }
                if(i==j)
                {printf("%d\n",i);/*braces must be used as if block contains two statements*/
                count++;}/*increment in counter variable for each prime number*/
                i++;/*increment in i for loop to be continued*/
    }
    while(count < n);/*test condition: printing n prime numbers up to sentinel variable*/


}


Thanking you !

1 comment: