If you have any query feel free to chat us!
Happy Coding! Happy Learning!
In C language, you can use a for loop to check if a number is prime or not. A prime number is a number that is divisible by only 1 and itself. To check if a number is prime, you can start the loop at 2 and increment it until it reaches half of the number. Within the loop, you can use the modulus operator (%), which returns the remainder when one number is divided by another, to check if the number is divisible by the current loop variable. If the remainder is 0, then the number is not a prime number and the loop can be exited.
Here's an example of C code that checks if a number is prime or not:
Copy code
#include <stdio.h>
int main() {
int n, i;
printf("Enter a positive integer: ");
scanf("%d", &n);
if (n==1) {
printf("1 is not a prime number.\n");
}
for (i = 2; i <= n / 2; ++i) {
if (n % i == 0) {
printf("%d is not a prime number.\n", n);
return 0;
}
}
printf("%d is a prime number.\n", n);
return 0;
}
This code prompts the user to enter a positive integer, checks if it is 1, which is not considered as prime number, and then uses a for loop to iterate through all integers from 2 to half of the entered number. It checks if the entered number is divisible by the current loop variable by using the modulus operator. If it is, it prints that the entered number is not a prime number and exits the loop. If the loop completes without finding a divisor, it prints that the entered number is a prime number.
Comments: 0