#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:
- Including the standard input-output library: We include the
stdio.h
header file to use theprintf
andscanf
functions for input and output.cCopy code#include <stdio.h>
- Main function: The execution of the program starts with the
main()
function.cCopy codeint main() { ... }
- 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 as1
(assuming the number is prime). If we find any divisor, we change it to0
(not prime).
int number, i, isPrime = 1;
- User input: We prompt the user to input a number using
printf
and store it in thenumber
variable usingscanf
.cCopy codeprintf("Enter an integer: "); scanf("%d", &number);
- 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 setisPrime = 0
and break the loop since the number is not prime.
if (number <= 1) { isPrime = 0; } else { for (i = 2; i <= number / 2; i++) { if (number % i == 0) { isPrime = 0; break; } } }
- Prime numbers are greater than 1, so if the number is less than or equal to 1, we directly set
- Displaying the result:
- If
isPrime
is still1
, the number is prime, so we print a message saying it is a prime number. - If
isPrime
is0
, we print that the number is not prime.
if (isPrime == 1) { printf("%d is a prime number.\n", number); } else { printf("%d is not a prime number.\n", number); }
- If
- 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.