#include <stdio.h>

int main() 
{
    int number, i, isPrime = 1;

    // Asking the user to input a number
    printf("Enter an integer: ");
    scanf("%d", &number);

    // Prime numbers are greater than 1
    if (number <= 1) {
        isPrime = 0;
    } else {
        // Checking divisibility from 2 to number/2
        for (i = 2; i <= number / 2; i++) {
            if (number % i == 0) {
                isPrime = 0;
                break; // If divisible, no need to check further
            }
        }
    }

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

    return 0;
}

Explanation:

  1. Including the standard input-output library: We include the stdio.h header file to use the printf and scanf functions for input and output.cCopy code#include <stdio.h>
  2. Main function: The execution of the program starts with the main() function.cCopy codeint main() { ... }
  3. Declaring variables:
    • number is used to store the number input by the user.
    • i is used as a loop counter for checking divisibility.
    • isPrime is a flag variable. It starts as 1 (assuming the number is prime). If we find any divisor, we change it to 0 (not prime).
    cCopy codeint number, i, isPrime = 1;
  4. User input: We prompt the user to input a number using printf and store it in the number variable using scanf.cCopy codeprintf("Enter an integer: "); scanf("%d", &number);
  5. Checking if the number is prime:
    • Prime numbers are greater than 1, so if the number is less than or equal to 1, we directly set isPrime = 0.
    • For numbers greater than 1, we check if the number is divisible by any integer from 2 to number/2 (because a number cannot have any divisor greater than its half). If we find a divisor, we set isPrime = 0 and break the loop since the number is not prime.
    cCopy codeif (number <= 1) { isPrime = 0; } else { for (i = 2; i <= number / 2; i++) { if (number % i == 0) { isPrime = 0; break; } } }
  6. Displaying the result:
    • If isPrime is still 1, the number is prime, so we print a message saying it is a prime number.
    • If isPrime is 0, we print that the number is not prime.
    cCopy codeif (isPrime == 1) { printf("%d is a prime number.\n", number); } else { printf("%d is not a prime number.\n", number); }
  7. Returning 0: The program returns 0 to indicate successful execution.cCopy codereturn 0

OUTPUT

Enter an integer: 7
7 is a prime number.

Summary:

The program checks divisibility starting from 2 up to number/2. If any divisor is found, the number is not prime. Otherwise, it’s a prime number.

A prime number is a number greater than 1 that has no divisors other than 1 and itself.

Leave a Reply

Your email address will not be published. Required fields are marked *

Verified by MonsterInsights