Check the Number is Prime or Not Example in C Programming Language

Check the Number is Prime or Not Example in C Programming Language

Avatar

 BY TEJAS




In this example, we will check a number is a Prime Number or Not.

First we will see
What is a Prime Number?
According to the mathematical definition of a prime number, "Prime number is a number which cannot be divided by the exactly whole number except itself and by the number 1".
For e.g. 5, 59, 97 are some prime numbers.



So let's take a turn to our example
In this example from the scanf() function, we will get the number from the user which number we have to check is it a "prime number or not".
We will do this example by using "If.....Else" statement and "For..." statement.

This example is little-bit confusing example for begginers.

We use for statement (i=2;i<=n/2;++i) Then we use "if....else" condition for a non-prime number.
You will get the idea when you see the program.


Note:- In Last of the Page there is a Program Code


Prime number in C

Below video shows Working of Program


main.c :-
    
      #include <stdio.h>
        int main() {
            int n, i, flag = 0;
            printf("Enter a positive number: ");
            scanf("%d", &n);
            for (i = 2; i <= n / 2; ++i) {
                // condition for non-prime numbers
                if (n % i == 0) {
                    flag = 1;
                    break;
                }
            }
            if (n == 1) {
                printf("1 is neither prime nor composite.");
            }
            else {
                if (flag == 0)
                    printf("%d is a prime number.", n);
                else
                    printf("%d is not a prime number.", n);
            }
            return 0;
        }
    


output :-
    
      Enter a Positive Number: 5
      5 is a prime number
    
  
    
      #include <stdio.h>
        int main() {
            int n, i, flag = 0;
            printf("Enter a positive number: ");
            scanf("%d", &n);
            for (i = 2; i <= n / 2; ++i) {
                // condition for non-prime numbers
                if (n % i == 0) {
                    flag = 1;
                    break;
                }
            }
            if (n == 1) {
                printf("1 is neither prime nor composite.");
            }
            else {
                if (flag == 0)
                    printf("%d is a prime number.", n);
                else
                    printf("%d is not a prime number.", n);
            }
            return 0;
        }
    


output :-
    
      Enter a Positive Number: 5
      5 is a prime number
    
  
Search
Advertisement
Share With
Follow us on
Advertisement