Menu
×
Tutorials Ms Word Tutorial Ms Excel Tutorial Ms PowerPoint Tutorial C Language Tutorial C++ Tutorial C Sharp Tutorial Visual Basic Tutorial HTML Tutorial CSS Tutorial JavaScript Tutorial WordPress Tutorial
     ❯   

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 Examples
OUTPUT
Enter 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 Examples

Let’s break down the code step by step:

  1. 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.

  1. 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.

  1. 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.

  1. 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.

  1. 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.

  1. Conclusion:
    The program prints all prime numbers within the specified range (num1 to num2) 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.
Spread the love
Scroll to Top
Scroll to Top