Write a C program to check whether a given number is prime or not.


 Problem Statement:

Write a C program to check whether a given number is prime or not.

Requirements:

  • The program should prompt the user to enter a positive integer.
  • It should determine whether the entered number is prime or not.
  • A prime number is a positive integer greater than 1 that has no positive integer divisors other than 1 and itself.
  • The program should display a message indicating whether the entered number is prime or not.

Examples:

  Enter a positive integer: 7
7 is a prime number. 
  Enter a positive integer: 6
6 is not a prime number.

  #include 
#include 

// Function to check if a number is prime
bool isPrime(int n) {
    if (n <= 1) {
        return false;
    }
    for (int i = 2; i * i <= n; i++) {
        if (n % i == 0) {
            return false;
        }
    }
    return true;
}

int main() {
    int num;
    printf("Enter a positive integer: ");
    scanf("%d", &num);

    if (num <= 0) {
        printf("Error: Please enter a positive integer.\n");
    } else {
        if (isPrime(num)) {
            printf("%d is a prime number.\n", num);
        } else {
            printf("%d is not a prime number.\n", num);
        }
    }

    return 0;
}
This program defines a function isPrime() to check whether a given number is prime or not. In the main() function, it prompts the user to enter a positive integer, calls the isPrime() function to determine if the entered number is prime, and displays the result accordingly. If the user enters a non-positive number, it displays an error message.

0 تعليقات

إرسال تعليق

Post a Comment (0)

أحدث أقدم