C Program to Print Alternate Prime Numbers from 1 to n

Ex: Write a C program to print alternate prime numbers from 1 to n. How to write a C program to print alternate prime numbers from 1 to n. C program to print alternate prime numbers from 1 to n.

Input from user:
Enter the number: 100

Expected output:
2 5 11 17 23 31 41 47 59 67 73 83 97


  • What is prime number?
Prime number means a number that is divisible only by 1 and itself.




  Step by step logic of the given program:


1. Accept input from user declare variable say no.

2. Declare e=2.

3. Run one outer for loop from 1 to no:
for(i=1;i<=no;i++)

4. Run one inner for loop from 1 to i and inside that check condition if i%j == 0 then increment c by 1:
for(j=1;j<=i;j++)
  {
  if(i%j==0)
   {
  c++;
   }
  } 


5. After that outside the inner for loop check if c==2 (it means if given number is prime) then, inside that if-statement check one more condition if e%2==0 means if e is even number then print value of (it prints   prime numbers only if e is completely divisible by 2, in short it prints alternate prime numbers):
if(c==2)
 {
 if(e%2==0)
 { 
 printf("%d ",i);
 }

6. After that, Outside the block of inner if statement increment value of e by 1.

7. Last make c=0.





  Program to Print Alternate Prime Numbers:


#include<stdio.h>
void main()
{
 int no,i,j,c=0,e;
 printf("Enter the number:\n");
 scanf("%d",&no);
 e=2;
 printf("Alternate Prime Number's Are:\n");
 for(i=1;i<=no;i++)
  {
  for(j=1;j<=i;j++)
  {
  if(i%j==0)
   {
  c++;
   }
  } 
 if(c==2)
 {
 if(e%2==0)
 { 
 printf("%d ",i);
 }
    e=e+1;
 }
 c=0;
 }
}


Above Program show's the following output:

C program to print alternate prime numbers from 1 to n, prime numbers




No comments:

Post a Comment

If you have any doubts, please discuss here...👇