ADVERTISEMENT
Prime Numbers Between Given Two Numbers
This C program is designed to find and print prime numbers within a specified range defined by two input numbers.
#include<stdio.h>
main()
{
int num1,num2,i,count=0,j;
printf("Enter a number 1\n");
scanf("%d",&num1);
printf("Enter a number 2\n");
scanf("%d",&num2);
printf("The Prime numbers between %d and %d are\n",num1,num2);
for(i=num1;i<=num2;i++)
{
count=0;
for(j=1;j<=i;j++)
{
if(i%j==0)
{
count++;
}
}
if(count==2)
{
printf("%d\n",i);
}
}
}C Programming ExamplesEnter a number 1
2000
Enter a number 2
2100
The Prime numbers between 2000 and 2100 are
2003
2011
2017
2027
2029
2039
2053
2063
2069
2081
2083
2087
2089
2099
C Programming ExamplesLet’s break down the code step by step:
- Variable Declarations:
int num1, num2, i, count = 0, j;
Here, the variables are declared to store the input numbers (num1 and num2), loop counters (i and j), and a counter (count) to determine the factors of each number.
- User Input:
printf("Enter a number 1\n");
scanf("%d", &num1);
printf("Enter a number 2\n");
scanf("%d", &num2);
The program prompts the user to enter two integer numbers (num1 and num2), defining the range for finding prime numbers.
- Prime Number Identification Loop:
printf("The Prime numbers between %d and %d are\n", num1, num2);
for (i = num1; i <= num2; i++) {
A for loop iterates through the numbers in the specified range.
- Factor Counting Loop:
count = 0;
for (j = 1; j <= i; j++) {
if (i % j == 0) {
count++;
}
}
Nested within the outer loop, another for loop is used to count the number of factors of the current number (i). The count variable is reset to 0 for each iteration.
- Prime Number Check:
if (count == 2) {
printf("%d\n", i);
}
After counting the factors, if the count is exactly 2, it means the current number has only two factors (1 and itself), indicating that it is a prime number. In such cases, the prime number is printed.
- Conclusion:
The program prints all prime numbers within the specified range (num1tonum2) by checking the number of factors for each integer in that range. If a number has exactly two factors, it is considered prime, and the program prints it.