# C Program to print Twin prime numbers between two ranges

Last updated on September 23, 2020

## What are Twin Primes Numbers? #

Pair of prime numbers which differ by 2 is called Twin Prime. For example, the first 4 twin primes are:

(3, 5), (11, 13), (17, 19), (29, 31)


The following is a C program to print Twin prime numbers between two ranges:

  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 /******************************************************* Program to print Twin prime numbers between two ranges *******************************************************/ #include // include stdio.h library int check_prime(int n); int main(void) { int start, end; printf("Enter start: "); scanf("%d", &start); printf("Enter end: "); scanf("%d", &end); for(int i = start; i < end; i++) { if(check_prime(i) && check_prime(i + 2)) { printf("{%d, %d}\n", i, i + 2); i = i + 1; } } return 0; // return 0 to operating system } int check_prime(int n) { if(n == 1) { return 0; } for(int i = 2; i < n; i++) { if(n % i == 0) { // number is not prime return 0; } } // number is prime return 1; } 

Expected Output: 1st run:

 1 2 3 4 5 6 7 8 Enter start: 1 Enter end: 50 {3, 5} {5, 7} {11, 13} {17, 19} {29, 31} {41, 43} 

2nd run:

 1 2 3 4 5 Enter start: 500 Enter end: 600 {521, 523} {569, 571} {599, 601} 

## How it works #

In line 19, we have a for loop that iterates over the numbers between the specified range.

In line 21, we call check_prime() number two times. Once with the number i and once with the number i + 2.

If the condition satisfies then i and i + 2 are twin primes. In line 23, we print the twin prime numbers and in line 24, we increment the counter i by 1, to check for the next number.