UncleCoder.com

UncleCoder.com

Free programming examples and instructions

C program to check whether a number is prime or not

C program for how to check the given number is prime or not

by Krishna viswambharan


Posted on 28 Sep 2017 Category: C Views: 356

Edited on 24 Jan 2018


C program to check whether a number is prime or not

A prime number is a natural number that has only one and itself as factors. For example 2,3,5,7,11,… are some of the prime numbers. Here we will see the c program to check whether a number is prime or not. Below is the C code for the same.

#include <stdio.h> 
#include <conio.h>
void main() 
{ 
       int n, i, count = 0; 
       printf("Enter any number n:"); 
       scanf("%d", &n); 
       for (i = 1; i <= n; i++)
 	   { 
           if (n % i == 0)
           { 
             count++; 
           }
 	   }
       if (count == 2)
       {
           printf("%d is Prime ",n); 
       } 
       else
 	   { 
           printf("%d is not a Prime number",n); 
       }
      getch();
} 

Suppose the given number is 7, then in the 'for loop' it executes until the i value becomes 7.

In the first iteration i=1, then it checks whether n%i==0, if it is true count variable increments. This process repeats until i=7. When i=7 for loop terminates and come out of the loop and execute the next if statement. while executing the statement (count==2), then the given number is prime.

output



Leave a Comment:


Advertisement