In this example, you will learn about C program to display prime numbers between two numbers interval or in a given range by the user with and without using the function.
A prime number is a natural number that is divisible by 1 and itself only.
For example: 2, 3, 5, 7 …
Please go through following articles of C programming to understand the concept of the program.
#include <stdio.h>
int main ()
{
int num1, num2, i, j, flag;
printf("Enter two numbers: ");
scanf("%d %d", &num1, &num2);
printf("Prime numbers between %d and %d are:\n", num1, num2);
// Displaying prime number between num1 and num2
for (i = num1 + 1; i < num2; ++i)
{
flag = 0; //flag is set to 0
for (j = 2; j <= i/2; ++j)
{
if (i % j == 0)
{
flag = 1;
break;
}
}
if (flag == 0) //if flag == 0, then display i
printf("%d\t", i);
}
return 0;
}
Output
[adsense1]
#include <stdio.h>
int displayPrimeNumber (int x); //function prototype
int main ()
{
int num1, num2, i, flag;
printf("Enter two numbers: ");
scanf("%d %d", &num1, &num2);
printf("Prime numbers between %d and %d are:\n", num1, num2);
// Displaying prime number between num1 and num2
for (i = num1 + 1; i < num2; ++i)
{
flag = displayPrimeNumber(i);
if (flag == 0) //if flag == 0, then display i
printf("%d\t", i);
}
return 0;
}
int displayPrimeNumber(int x)
{
int j, flag = 0;
for (j = 2; j <= x/2; ++j)
{
if (x % j == 0)
{
flag = 1;
break;
}
}
return flag;
}
Output
Explanation
The first example displays all prime numbers without using user defined function.
However, we have used displayPrimeNumber
user defined function for same purpose.
The sole purpose of displayPrimeNumber
user defined function is to check the number is prime or not and set the value of flag
.