c
  1. c-program-to-display-prime-numbers-between-intervals-using-function

Program to Display Prime Numbers Between Intervals Using Function - ( C Programs )

Example

#include <stdio.h>

int checkPrimeNumber(int n);

int main()
{
    int n1, n2, i, flag;

    printf("Enter two positive integers: ");
    scanf("%d %d", &n1, &n2);

    printf("Prime numbers between %d and %d are: ", n1, n2);

    for(i=n1+1; i<n2; ++i)
    {
        // flag will be equal to 1 if i is prime
        flag = checkPrimeNumber(i);

        if(flag == 1)
            printf("%d ",i);
    }

    return 0;
}

// Function to check prime number
int checkPrimeNumber(int n)
{
    int j, flag = 1;

    for(j=2; j <= n/2; ++j)
    {
        if (n%j == 0)
        {
            flag = 0;
            break;
        }
    }

    return flag;
}

Output

Enter two positive integers: 2 50
Prime numbers between 2 and 50 are: 3 5 7 11 13 17 19 23 29 31 37 41 43 47

Explanation

In this program, we have two user defined functions defined, main() and checkPrimeNumber(). In the main() function, the user enters two positive integers, which are stored in variables n1 and n2. The for loop is used to iterate from n1+1 to n2-1. The integer i in each iteration checks with the checkPrimeNumber() function, if it is a prime number or not. If the flag variable returned by checkPrimeNumber() is equal to 1, it indicates that the number is a prime number and it is printed on the screen.

In the checkPrimeNumber() function, the integer n is passed as an argument and checked for being a prime number. The function also returns a flag variable of type integer, which is equal to 1 if the number is prime, and 0 if it is not, according to the for loop logic.

Use

This program is used to display the prime numbers between two intervals using a user defined function checkPrimeNumber().

Summary

This program takes input of two positive integers from the user and calculates and displays the prime numbers between them using a user defined function checkPrimeNumber(). The checkPrimeNumber function checks if a number is prime or not and returns a flag variable to the main() function to indicate if the number should be displayed or not.

Published on: