C Program To Check Given Number is Prime or Not

C Program to check given number is prime or not

A prime number is a number which is only divisible by one and itself, prime number programs are common in C programming language. Most of the times we get a program to find whether given number is prime or not, it is a commonly asked program in exams and practicals. In this article we will learn to create a C Program to check given number is prime or not.

C Programming by HowToDoHTD

Description of C Program to Check given number is prime or not.

In this program we will use two integer type variables, 'n' to store the number entered by the user and 'c' with initial value 2. We will first ask the user to insert a number and then will store that number in variable 'n'. Then, run a for loop in which initial value of 'c' is 2, 'c' is less then equal to 'n-1' and post increment in 'c' by +1, in this loop we will check if 'n%c= =0' using if statement. If it is equal to 0 then we will print 'number is not prime', and will close the loop, then will again use if statement to check if 'c= =n', if condition true we will print 'number is prime'.

C Program to check given number is prime or not


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


This is how you can create a c program to check given number is prime or not.


Previous
Next Post »