C Program For Prime Numbers

C program for Prime Numbers

In this Program, we will find the prime numbers till n numbers, this program will print a list of prime numbers, that user wants to print. A number is called Prime number if, it is divisible only by one and itself, 2 is the only even prime number, example of prime numbers 2,3,5,7,11,13 etc.


C programming by howtodohtd


Description of Prime number Program

In this program we will take 3 integer type variables, 'n' to store how much prime numbers user wants to print, variable 'i' with initial value 3 , 'count' for running the loop and 'c' for assigning values in the loop. Further, we will use if else statement and for loop, that will be used for finding prime numbers and printing them. After, receiving the value of 'n' from user we will check, if user has inserted a right value or have inserted 0 by the help of if statement. Then after, we will start for loop by the help of 'count' and will put the initial value equal to 2 and run the loop until count would become equal to 'n'. Then in the previous loop we will again run a for loop, initial value of 'c' equal to 2, loop will run till value of 'c' becomes equal to 'i' with post increment of 1. under this loop we will use if statement to check if i%c= = 0, if it is is we will put break statement just next to it. Then, continue with another if statement to check whether c = = i, and then, will print the value of i, again with increment in the value of count, statement would be repeated. 

C program for prime numbers


#include<stdio.h>
 
int main()
{
   int n, i = 3, count, c;
 
   printf("Enter the number of prime numbers required\n");
   scanf("%d",&n);
 
   if ( n >= 1 )
   {
      printf("First %d prime numbers are :\n",n);
      printf("2\n");
   }
 
   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++;
   }
 
   return 0;
}

Output

output

The user entered 10 as the value of n and program has successfully printed the first 10 prime numbers.

This was C program for prime numbers if you face some problem please mention in comment.
Thank you.
Previous
Next Post »