Prime Number Program Coding Example in C Programming Language - 3 Examples

Algorithm


Prime Number has some following conditions to become a Full prime number. Prime Number Cases when it will be fullfilled the requirement of prime number:

  1. Prime number should be a whole number
  2. Prime number should be greater than 1
  3. Prime number should have only 2 factors. The factors are 1 and the number itself.

Examples of Prime Numbers : 2, 3, 5, 7, 11, 13, 17, 19, 23 etc.
Examples of non-Prime Numbers : 4, 6, 8, 9, 10, 12, 14, 15, 16

 

 

 

 

Code Examples

#1 Prime Number Checker Using C Programming

Code - C Programming

#include <stdio.h>

int main() {
  int n, i, flag = 0;
  printf("Enter a positive integer: ");
  scanf("%d", &n);

  for (i = 2; i <= n / 2; ++i) {
    if (n % i == 0) { // Check a non-prime number
      flag = 1;
      break;
    }
  }

  if (n == 1) {
    printf("1 is neither prime nor composite.");
  } 
  else {
    if (flag == 0)
      printf("%d is a prime number.", n);
    else
      printf("%d is not a prime number.", n);
  }

  return 0;
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
Enter a positive integer: 2

Output

x
+
cmd
2 is a prime number.

#2 Prime Number or Composite number Check using C Programming

Code - C Programming

#include <stdio.h>

int 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 a prime number.\n", n);

  return 0;
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
Enter a number to check if it's prime: 9

Output

x
+
cmd
9 is a composite number.

#3 Prime Number solution Using Function C Programming

Code - C Programming

#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 a prime number.\n", n);
   else
      printf("%d is not a 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;
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
2

Output

x
+
cmd
2 is a prime number.

Demonstration