Write a C Program to Check Whether a Number is Prime or Not Prime.

Prince Patel
By -
0

Write a C Program to Check Whether a Number is Prime or Not Prime.



In this Article, you will learn how to check whether a number is Prime or Not Prime.

A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. In other words, a prime number is only divisible by 1 and itself. A number that is not prime is called a composite number. To check whether a given number is prime or not, we need to check if it has any divisors other than 1 and itself.

Here's a C program to check whether a number is prime or not:

#include<stdio.h>
#include<conio.h>

void main()
{
    int num, isPrime = 1;

    // Input number from user
    printf("Enter a positive integer: ");
    scanf("%d", &num);

    // 0 and 1 are not prime numbers, so check if the number is greater than 1
    if (num > 1) {
        // Loop to check for factors of the number
        for (int i = 2; i * i <= num; i++) {
            if (num % i == 0) {
                isPrime = 0;
                break; // No need to continue the loop if a factor is found
            }
        }
    } else {
        isPrime = 0; // Numbers less than or equal to 1 are not prime
    }

    // Output the result
    if (isPrime) {
        printf("%d is a prime number.\n", num);
    } else {
        printf("%d is not a prime number.\n", num);
    }
}


  • The program starts by declaring the necessary variables num (to store the input number) and isPrime (to store whether the number is prime or not).
  • It then prompts the user to enter a positive integer.
  • The program checks if the entered number is greater than 1 (prime numbers are greater than 1). If the number is not greater than 1, it immediately concludes that it's not a prime number and sets isPrime to 0.
  • If the number is greater than 1, the program enters a loop that runs from 2 up to the square root of the number (as any factor of the number will be less than or equal to its square root). In each iteration, it checks if the number is divisible by the loop variable i. If it is divisible, isPrime is set to 0, indicating that the number is not prime, and the loop is terminated using the break statement.
  • After the loop, the program checks the value of isPrime and prints an appropriate message indicating whether the number is prime or not.
When you run this program, it will take two integer inputs from the user, add them together, and then display the sum on the screen. For example:

Output:



Please note that the program assumes that the user enters a positive integer as input. It does not handle invalid inputs or negative numbers. For a more robust implementation, additional input validation can be added.
Tags:

Post a Comment

0Comments

Post a Comment (0)