Exercise:
Write a C Program to display prime numbers between intervals using function.
Click Here to View the Solution!
#include <stdio.h>
int checkPrimeNumber(int num);
int main() {
int num1, num2, i, flag;
printf("Enter two positive integers: ");
scanf("%d %d", &num1, &num2);
printf("Prime numbers between %d and %d are: ", num1, num2);
for (i = num1 + 1; i < num2; ++i) {
flag = checkPrimeNumber(i);
if (flag == 1)
printf("%d ", i);
}
return 0;
}
int checkPrimeNumber(int num) {
int j, flag = 1;
for (j = 2; j <= num / 2; ++j) {
if (num % j == 0) {
flag = 0;
break;
}
}
return flag;
}
Click Here to View the Output!
Enter two positive integers: 3 9
Prime numbers between 3 and 9 are: 5 7
Click Here to View the Explanation!
- This program is used to display all the prime numbers between the intervals using a user-defined function.
- A user-defined function integer
checkPrimeNumber
is declared with an integer a as its parameter. - In
main()
, The program requests the user to enter two positive integers as intervals and stores them in the variablesnum1
andnum2
using thescanf()
function. - A
for loop
is initialized that will iterate betweeni = num1
andi < num2
. - The
checkPrimeNumber
function takesi
as a parameter and stores the output in the variableflag
. Ifflag
will be equal to 1, the number will be a prime number and will be printed. - The
checkPrimeNumber
will be formed that will use afor loop
which will iterate betweenj = 2
andj = num/2
and will incrementj
in each iteration. Aflag
will be set to 1 initially. - An
if statement
will check whethernum
is exactly divisible byj
, if true, will turnflag
to 0. Else, theflag
will remain 1 and the number will be a prime number.