unique, ad-free, freemium downloads

19 November 2017

How To : A C Program to Print N Prime Numbers

PRIME NUMBERS:

prime number (or a prime) is a natural number greater than 1 that has no positive divisors other than 1 and itself.The first few prime numbers include   2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, etc.

LOGIC:

To generate prime numbers in C to a specific number, we have to make two loops.One will generate numbers from 2 to that specific number while another will generate numbers to check whether the number is a multiple of its predecessors or not.

CODE:

#include <stdio.h>
int main()
{int num ;
printf("Please enter the number until you want to print the prime numbers:");
scanf("%d",&num);//Number should be Natural Number
printf("2\n"); // 2 is printed forcefully because every loop starts with two
for(int a=2 ; a<=num ;a++)//This loop helps us to generate numbers from 2 to given number
 {
  for(int b=2; b < a ;b++ )//This loop helps us to generate numbers from 2 to 'a - 1'
  {
  if (a % b == 0)//So that loop must break whenever a is multiple of b
  break ;
  if (b == a - 1 )//So that a is printed only one time
  printf("%d\n",a);
 }
   }
  system("pause");
 return 0;
}

OUTPUT:


No comments:

Post a Comment