In C language, you can check if a given number is a prime number or not using a loop and some basic mathematical operations. A prime number is a positive integer greater than 1 that has no positive integer divisors other than 1 and itself. Here is an example program that checks if a given number is prime or not:
c#include <stdio.h>
int main() {
int n, i, flag = 0;
printf("Enter a positive integer: ");
scanf("%d", &n);
for(i = 2; i <= n/2; ++i) {
// condition for non-prime number
if(n%i == 0) {
flag = 1;
break;
}
}
if (n == 1) {
printf("1 is not a prime number.");
}
else {
if (flag == 0)
printf("%d is a prime number.", n);
else
printf("%d is not a prime number.", n);
}
return 0;
}
In this program, the user is prompted to enter a positive integer. The program then uses a loop to check if the number is divisible by any integer between 2 and n/2. If the number is divisible by any integer, then it is not a prime number and the flag
variable is set to 1. If the number is not divisible by any integer, then it is a prime number and the flag
variable remains 0.
Finally, the program checks the value of the flag
variable and prints an appropriate message indicating whether the number is prime or not. Note that 1 is not considered a prime number, so a separate condition is included to handle the case when the user enters 1.
Comments
Post a Comment