Tuesday, November 22, 2022
HomeFun With ProgrammingProgramsPrime Number Program In C

Prime Number Program In C

Today of in this Prime Number Program In C program of C we will see how we can find whether the number given by the user is prime or not?

first of all, let’s understand what is a prime number?

A prime number is a number that is only divisible by 1or itself,

it will never be divisible by any other number.

C Program For Finding Prime Numbers

#include<stdio.h>
int main()

{
    /* code */
    int num,i;
    int flag = 0;
    printf("Enter the number to check whether it is prime or not\n");
    scanf("%d",&num);
    for(i = 2;i<=num/2;i++)
    {
        // condition for check that num is not prime
        if(num%i==0)
        {  
            flag =1;
            break;
        }
       
    }
    if(flag==1)
    {
         printf("the %d is not prime",num);
    }
    else
    {
        printf("the %d is prime",num);
    }
    return 0;
}

Find The Number Is Prime Or Not In C

  • In the above How To Check Given Number Is Prime Or Not In C program, I have taken 3 variables.
  • num for taking the input from the user and i to run the loop .
  • and I have initially set the flag to zero.
  • that means we have accepted that the number entered by the user is already prime.
  • Remember that 1 is neither prime nor composite number. That’s why we initialized i to 2.
  • After that, whatever number the user will enter, we will check with the condition by running the loop till half the number of that number.
  • If the number entered by the user can be divided by another number then,
  • it means the number is composite number not prime number, and we will set the flag to 1 and we will get out from the loop.
  • And for that, I have used the break statement to exit the loop.
  • Now we will check whether the flag is 1 Or zero . If the flag is 1 then the number entered by the user is not a prime number otherwise a number is a prime number.
  • so by this way, you can find the number entered by the user is prime or not.

I hope now you will understand how easily we can find the given number is prime or not? In C. If you have any queries or suggestions regarding this article, you can ask us by commenting on us in the below comment section.

You May Also Like

Suhashini Mishrahttps://rkrknowledge.com/
Suhasini Mishra from India passionate UI UX Developer | Content Writer | Content Researcher | Ionic Developer

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -

Stay Connected

29FansLike
36FollowersFollow
500SubscribersSubscribe

Most Popular

Recent Comments