C Program to Display Prime Numbers Between Two Intervals Using Functions
Last Updated :
08 Jun, 2023
Prime numbers have only 2 factors, 1 and themselves. For example, 2,3, 5, 7, 9,… are the first 5 prime numbers. Here we will build a C program to display prime numbers between two intervals using functions using 2 approaches, for loop and while loop.
Example
Input: num1 = 2, num2 = 10
Output: Prime numbers between 2 and 10 are: 2 3 5 7
Explanation: The prime numbers between the given intervals 2(starting limit) and 10(ending limit) are 2 3 5 and 7
Using For Loop
Below is the C program to display prime numbers between two intervals using functions and for loop:
C
#include <stdio.h>
int checkPrimeNumber( int number)
{
int i, f = 1;
for (i = 2; i <= number / 2; ++i)
{
if (number % i == 0)
{
f = 0;
break ;
}
}
return f;
}
int main()
{
int num1 = 2, num2 = 10, j, f;
printf ( "Prime numbers between %d and %d are: " ,
num1, num2);
for (j = num1; j < num2; ++j)
{
f = checkPrimeNumber(j);
if (f == 1)
{
printf ( "%d " , j);
}
}
return 0;
}
|
Output
Prime numbers between 2 and 10 are: 2 3 5 7
Using While Loop
Below is the C program to display prime numbers between two intervals using functions and while loop:
C
#include <stdio.h>
int isPrime( int number)
{
int i;
for (i = 2; i <= number / 2; i++) {
if (number % i == 0) {
return 0;
}
}
return 1;
}
int main()
{
int num1 = 2, num2 = 10;
printf ( "The prime numbers between %d to %d are: " ,
num1, num2);
while (num1 <= num2)
{
if (isPrime(num1))
{
printf ( "%d, " , num1);
}
num1++;
}
return 0;
}
|
Output
The prime numbers between 2 to 10 are: 2, 3, 5, 7,
Share your thoughts in the comments
Please Login to comment...