To display prime numbers between two intervals in a C program, you can use a loop to check each number in the specified range for primality. Here's a C program to do just that:
#include <stdio.h>
// Function to check if a number is prime
int isPrime(int num) {
if (num <= 1) {
return 0; // 0 and 1 are not prime numbers
}
for (int i = 2; i * i <= num; i++) {
if (num % i == 0) {
return 0; // If divisible by any number between 2 and sqrt(num), it's not prime
}
}
return 1; // It's a prime number
}
int main() {
int start, end;
printf("Enter the start of the interval: ");
scanf("%d", &start);
printf("Enter the end of the interval: ");
scanf("%d", &end);
printf("Prime numbers between %d and %d are: ", start, end);
// Ensure that start is at least 2 to handle prime numbers correctly
if (start < 2) {
start = 2;
}
for (int i = start; i <= end; i++) {
if (isPrime(i)) {
printf("%d, ", i);
}
}
printf("\n");
return 0;
}
In this program, we first define a function isPrime
that checks if a number is prime. Then, in the main
function, we take the user's input for the start and end of the interval and use a loop to iterate through the numbers in that interval, checking if each number is prime using the isPrime
function. If a number is prime, it is printed to the console.
Make sure to include the necessary header files and compile this program to run it. The output of the C program to display prime numbers between two intervals might look when you run it:
Enter the start of the interval: 10
Enter the end of the interval: 50
Prime numbers between 10 and 50 are: 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47,
In this example, the user entered the start of the interval as 10 and
the end as 50. The program then listed all the prime numbers within that
range.