English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

C language basic tutorial

C language flow control

C Language Functions

C Language Arrays

C Language Pointers

C Language Strings

C language structures

C language files

C others

C language reference manual

C program to display all prime numbers between two numbers

Comprehensive Collection of C Programming Examples

In this example, you will learn how to print all prime numbers between the two numbers entered by the user.

To understand this example, you should understand the followingC programming languageTopic:

Display prime numbers between two intervals

#include <stdio.h>
int main() {
   int low, high, i, flag;
   printf("Enter two numbers (separated by space): ");
   scanf("%d %d", &low, &high);
   printf("%d and %d between prime numbers: ", low, high);
   //Iterate until low is not equal to high
   while (low < high) {
      flag = 0;
      // ignore numbers less than2of the number
      if (low <= 1) {
         ++low;
         continue;
      }
      //If low is not prime, then flag is1
      for (i = 2; i <= low / 2; ++i) {
         if (low % i == 0) {
            flag = 1;
            break;
         }
      }
      if (flag == 0){
          printf("%d ", low);
      }
         
      ++low;
   }
   return 0;
}

Output the result

Enter two numbers (separated by space): 20 
50
2and 05between 0 prime numbers are: 23 29 31 37 41 43 47

In this program, the while loop is iterated (high-low-1times.

In each iteration, check if low is prime, and increase the value of low1until low equals high.

visit this page to learn about howcheck if a number is primefor more information.

If the user enters the larger number first, the above program will not work properly. You canSwap numbersto solve this problem.

When the larger number is entered first, display prime numbers

#include <stdio.h>
int main() {
   int low, high, i, flag, temp;
   printf("Enter two numbers (separated by space): ");
   scanf("%d %d", &low, &high);
   //If low is greater than high, swap the numbers
   if (low > high) {
      temp = low;
      low = high;
      high = temp;
   }
   printf("%d and %d between prime numbers: ", low, high);
   while (low < high) {
      flag = 0;
      //ignore numbers less than2of the number
      if (low <= 1) {
         ++low;
         continue;
      }
      for (i = 2; i <= low / 2; ++i) {
         if (low % i == 0) {
            flag = 1;
            break;
         }
      }
      if (flag == 0)
         printf("%d ", low);
      ++low;
   }
   return 0;
}

Visit this page to learn howBy creating user-defined functionsComeDisplay all prime numbers between two time intervals

Comprehensive Collection of C Programming Examples