C Program to Print All Prime Numbers Between Two Numbers
This program takes two integers as input and prints all the prime numbers that fall between those two numbers (inclusive).
Concept Overview
A prime number is a number greater than 1 that has no divisors other than 1 and itself. The program checks each number in the given range and determines if it is prime using a loop and conditional checks.
Program
C
#include <stdio.h>
// Function to check if a number is prime
int isPrime(int n) {
if(n <= 1) return 0;
for(int i = 2; i*i <= n; i++) {
if(n % i == 0) return 0;
}
return 1;
}
int main() {
int lower, upper;
printf("Enter two numbers: ");
scanf("%d %d", &lower, &upper);
printf("Prime numbers between %d and %d are:\n", lower, upper);
for(int i = lower; i <= upper; i++) {
if(isPrime(i)) {
printf("%d ", i);
}
}
printf("\n");
return 0;
}
Sample Output
Enter two numbers: 10 30 Prime numbers between 10 and 30 are: 11 13 17 19 23 29
Explanation
- The program uses a nested loop — the outer loop iterates through each number in the given range.
- The inner loop checks whether the current number is divisible by any number from 2 up to its square root.
- If a number is not divisible by any of these, it is identified as a prime number.
- All prime numbers are printed in a single line separated by spaces.
Note: Note: This program assumes the first number entered is less than or equal to the second. You can add a swap condition to handle reversed input.
Codecrown