This is a C program to find prime numbers in a given range.
The program takes the range and finds all the prime numbers between the range and also prints the number of prime numbers.
1. Take the range of numbers between which you have to find the prime numbers as input.
2. Check for prime numbers only on the odd numbers between the range.
3. Also check if the odd numbers are divisible by any of the natural numbers starting from 2.
4. Print the prime numbers and its count.
5. Exit.
Here is source code of the C program to calculate the prime numbers in a given range. The C program is successfully compiled and run on a Linux system. The program output is also shown below.
#include <stdio.h>
#include <stdlib.h>
void main()
{
int num1, num2, i, j, flag, temp, count = 0;
printf("Enter the value of num1 and num2 \n");
scanf("%d %d", &num1, &num2);
if (num2 < 2)
{
printf("There are no primes upto %d\n", num2);
exit(0);
}
printf("Prime numbers are \n");
temp = num1;
if ( num1 % 2 == 0)
{
num1++;
}
for (i = num1; i <= num2; i = i + 2)
{
flag = 0;
for (j = 2; j <= i / 2; j++)
{
if ((i % j) == 0)
{
flag = 1;
break;
}
}
if (flag == 0)
{
printf("%d\n", i);
count++;
}
}
printf("Number of primes between %d & %d = %d\n", temp, num2, count);
}
1. User must take the range as input and it is stored in the variables num1 and num2 respectively.
2. Initially check whether num2 is lesser than number 2.If it is, then print the output as “there are no prime numbers”.
3. If it is not, then check whether num1 is even.If it is even, then make it odd by incrementing the num1 by 1.
4. Using for loop starting from num1 to num2, check whether the current number is divisible by any of the natural numbers starting from 2.Use another for loop to do this.Increment the first for loop by 2, so as to check only the odd numbers.
5. Firstly initialize the variables flag and count to zero.
6. Use the variable flag to differentiate the prime and non-prime numbers and use the variable count to count the number of prime numbers between the range.
7. Print the prime numbers and variable count separately as output.
Case:1 Enter the value of num1 and num2 70 85 Prime numbers are 71 73 79 83 Number of primes between 70 and 85 = 4 Case:2 Enter the value of num1 and num2 0 1 There are no primes upto 1
Sanfoundry Global Education & Learning Series – 1000 C Programs.
Here’s the list of Best Books in C Programming, Data-Structures and Algorithms
- Check C Books
- Apply for Computer Science Internship
- Check Computer Science Books
- Practice Computer Science MCQs
- Practice BCA MCQs