C Program to determine whether given number is prime or not

      A natural number which is perfectly divisible by 1 and the number itself then that number is called as prime. So, it has only two divisors i.e., 1 and the number itself. This program finds whether given number is prime or not by checking the remainder of that number when divided by a number(every natural number) starting from 2 to (n/2). So if we get remainder as zero means it has divisors other than 1 and the number itself, Which implies that the given number is not prime number otherwise given number is a prime number.

c program to determine whether a number is prime number or not



Source Code :

#include<stdio.h>
int main( )
{
	int n, r, d=2;
	printf( "\n Enter the number :");
	scanf("%d", &n);                                    // Step 1
	r = 1;
	while(d <= n/2)                                    // Step 2 
	{
		r = n%d;                                   // Step 2 (i)
		if(r == 0) 
			break;                             // Step 2 (ii)
		d++;                                       // Step 2 (iii)
	}
	if(r==0)
		printf("\n IT IS NOT A PRIME");        // Step 3
	else
		printf("\n IT IS A PRIME");            // Step 3 
	return 0;
}


edit-code-image

Sample Test cases :

1. Enter the number : 5
   IT IS A PRIME

2. Enter the number : 10
   IT IS NOT A PRIME
   
3. Enter the number : 11
   IT IS A PRIME

Explanation for Prime Number:

Step 1 : The program reads a number from the user using scanf() function.

Step 2 : The while loop is iterated from 2 to (n/2) to find out remainder when given number is divided by every natural number staring from 2 to (n/2). Generally you’ll find programs checking till n which is of no use 😉

Step 2 (i) : The remainder, When given number is divided by the ‘d’ is found and stored in ‘r’.

Step 2 (ii) : If we get ‘r’ as zero in middle this implies that given number is not a prime number, So we exit from the loop and move to step3.

Step 2 (iii): If remainder is non-zero then we increment the loop counter to next number.

Step 3 : Until loop ends if ‘r’ is non-zero then it implies that given number is prime number.

More Insights:

More Information

Explore C Programs:C Programs