What are prime numbers?

Prime numbers are those numbers which are not divisible by any integer without 1 and itself. Composite number can be divisible by at least an integer without 1 and that number itself. 2 is the only even prime number as every even number can be divisible by 2.

Some example of prime numbers are 2, 3, 5, 7, 11, 13, 17, 19, 23……. . Prime numbers have many applications in not only mathematics but also in computer science. In this article we will discus more and give some example C program related to prime numbers in C programming.

Checking prime numbers in C

#include<stdio.h>
int main(){
  int num, i;

  printf("Enter a number to check it prime or not : ");
  scanf("%d", &num);

  for (i = 2; i <= num/2; i++){
    if (num % i == 0){
      printf("\n%d is not a prime number.\n", num);
      break;
    }
  }

  if (i == num/2 + 1){
    printf("\n%d is a prime number.\n", num);
    }
  return 0;
}

Output of this prime number checking program

prime numbers checking program in c

Check prime number using function in C

// checking prime number in C
#include<stdio.h>

int checkPrime(int num){     // function to check prime
   int i;

   for (i = 2; i <= num - 1; i++)
   {
      if (num % i == 0)
     return 0;
   }
   if (i == num)
      return 1;
}

int main(){        // main program
   int givenNum, result;

   printf("Enter any number to check : ");
   scanf("%d",&givenNum);

   result = checkPrime(givenNum);      // calling function

   if (result == 1){
      printf("\n%d is a prime number.\n", givenNum);
   }else{
      printf("\n%d is not a prime number.\n", givenNum);
    }
   return 0;
}

Output will be as follows

checking prime number in c, prime checker

Printing the list of prime numbers in C

// Printing list of prime numbers using C language
#include <stdio.h>
int main(){
  int num, a = 3, count, b;

  printf("How many prime number do you want to print?\n");
  scanf("%d", &num);

  if (num >= 1){
    printf("The first %d prime numbers are : \n",num);
    printf("2\n");
  }

  for (count = 2; count <= num;){
    for (b = 2; b <= a - 1; b++){
      if (a%b == 0){
        break;
      }
    }
    if (b == a){
      printf("%d\n", a);
      count++;
    }
    a++;
  }
  return 0;
}

Output for this prime number printing program:

printing prime numbers list in c programming

You can print any integer using other methods too. So, try to write a program in your own.

Previous pageSum of digits in C

Next pageSum of natural numbers in C