Prime number program in C

Write A Program To Check Whether a given Number Is Prime Or Not?

Prime number program in C language to check whether a number is prime or composite, to print prime numbers. A number is prime if it's divisible only by one and itself.

Prime number in C language

#include<stdio.h>
#include<conio.h>
void main()
{
  int n, i = 3, count, c;
  printf("Enter the number of prime numbers to print\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++;
  }
  getch();
}
C program for prime number or not

#include<stdio.h>
#include<conio.h>
void main()
{
  int n, c;
  printf("Enter a number to check if it's prime\n");
  scanf("%d", &n);
  for (c = 2; c <= n/2; c++)
  {
    if (n%c == 0)
    {
      printf("%d is a composite number.\n", n);
      break;
    }
  }
  if (c == n/2 + 1)
    printf("%d is prime.\n", n);
  getch();
}

C program for prime number using function


#include<stdio.h>
int check_prime(int);
int main()
{
   int n, result;
 
   printf("Enter an integer to check whether it's prime or not.\n");
   scanf("%d",&n);
   result = check_prime(n);
 
   if (result == 1)
      printf("%d is prime.\n", n);
   else
      printf("%d isn't prime.\n", n);
 
   return 0;
}
int check_prime(int a)
{
   int c;
 
   for (c = 2; c <= a - 1; c++)
   {
      if (a%c == 0)
     return 0;
   }
   if (c == a)
      return 1;
}

No comments:

Post a Comment