Write a c program to check prime number.

Ram Pothuraju

 #include <stdio.h>


int main()

{

    int n, i, flag = 0;


    printf("Enter a positive integer: ");

    scanf("%d", &n);


    // 0 and 1 are not prime numbers

    if (n == 0 || n == 1)

    {

        printf("%d is not a prime number.", n);

    }

    else

    {

        for (i = 2; i <= n/2; ++i)

        {

            // If n is divisible by any number between 2 and n/2, it is not prime

            if (n%i == 0)

            {

                flag = 1;

                break;

            }

        }


        if (flag == 0)

        {

            printf("%d is a prime number.", n);

        }

        else

        {

            printf("%d is not a prime number.", n);

        }

    }


    return 0;

}



In this program, we first take a positive integer as input from the user. Then, we check if the number is 0 or 1, which are not prime numbers. If the number is neither 0 nor 1, we loop through all the numbers from 2 to n/2 and check if n is divisible by any of these numbers. If n is divisible by any of these numbers, we set a flag variable to 1 and break out of the loop. Finally, we check the value of the flag variable and print the appropriate message to indicate whether the number is prime or not.

Post a Comment

0Comments

Post a Comment (0)