prime numbers c
To generate prime numbers in C, you can use the following code snippet:
#include <stdio.h>
int isPrime(int num) {
if(num <= 1) {
return 0;
}
for(int i = 2; i * i <= num; i++) {
if(num % i == 0) {
return 0;
}
}
return 1;
}
int main() {
int n;
printf("Enter a number: ");
scanf("%d", &n);
printf("Prime numbers less than or equal to %d are: ", n);
for(int i = 2; i <= n; i++) {
if(isPrime(i)) {
printf("%d ", i);
}
}
return 0;
}
This code defines a function isPrime()
that checks if a number is prime. In the main()
function, the user is prompted to enter a number. Then, a loop iterates from 2 to the entered number and calls isPrime()
for each number. If the number is prime, it is printed.