In this article, I will show you how you can create a program for checking prime number using a while loop in C, but before we proceed further, let's clear the definition of prime number first.

Prime Number: A Prime Number is a number greater than 1 and which is only divisible by 1 and the number itself. For example, 13 is a prime number as it is divisible by 1 and itself, but 4 is not a prime number as it can be divided by 2.

So, to find if a number if prime or not, we can check is number is divisible by any number from 2 to N, if it is divisible by any number between this, then it is not primer otherwise it is prime.

Let's create a program in which we will be checking all the prime number available below 50 using while loop

``````#include <stdio.h>
#include <math.h>

int main(void)
{
int max = 50;
int current = 4;
int checker = 2;
do{
if(checker > sqrt((double)current))
{
checker = 2;
// number is prime print it
printf("%d is prime\n",current);
current++;
}
else if(current % checker == 0)
{
/* number is not a prime, let's continue */
checker = 2;
current++;
}
else
checker++;
}while(current < max);
}``````

Cases which we have considered in the above program:

• Our current number is divisible by the test variable then the number is NOT prime, increase the current number and reset the test variable.
• Our test variable is greater than the square root of the current number. By definition, it CANNOT divide the current number, so the current number has to be prime (we have tried all numbers lower than the square root of the current number and none of them divide it). Increase the current number and reset the test variable.
• Lastly, if either above case isn't true, we have to try the next number higher. Increment the test variable.

The output of the above code will be as below

``````5 is prime
7 is prime
11 is prime
13 is prime
17 is prime
19 is prime
23 is prime
29 is prime
31 is prime
37 is prime
41 is prime
43 is prime
47 is prime``````

You can check the above program here https://onlinegdb.com/BJ8cObm17 ### Program to check if a number is prime or not by taking user input

In this program, we will take user's number and check if it Prime or not

`````` #include <stdio.h>

void main() {
int no, i, f;

printf("Enter any number: ");
scanf("%d", & no);
f = 0;
i = 2;
while (i <= no / 2) {
if (no % i == 0) {
f = 1;
break;
}
i++;
}
if (f == 0)
printf(" %d is Prime Number", no);
else
printf("%d  Not Prime Number", no);

}``````

Executing the above code by entering number 5, the output will be as below

``````Enter any number: 5
5 is Prime Number `````` You can try it