C program to find prime numbers between given interval using functions

Write a function in C programming to find all prime numbers between two intervals. How to find all prime numbers between two intervals using the concept of functions. Display all prime numbers between a given range using functions in C programming.

Example:
Input lower limit: 10
Input upper limit: 50
Output prime numbers between 10-50 are: 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47

Required knowledge

Basic C programming, Function, Prime numbers

If you have gone through my previous posts you probably know how to check whether a number is prime or not and also how to find all prime numbers between 1 to n using loops and checking whether a number is prime or not using function. If you haven't then it is highly recommended to go through above posts.

Program to find all prime numbers between two given intervals using functions

/**
 * C program to list all prime number between an interval using function.
 */

#include <stdio.h>


/* Function declarations */
int isPrime(int num);
void printPrimes(int lowerLimit, int upperLimit);



int main()
{
    int lowerLimit, upperLimit;
    
    printf("Enter the lower and upper limit to list primes: ");
    scanf("%d%d", &lowerLimit, &upperLimit);
    
    //Calls the function to print all primes between the given range.
    printPrimes(lowerLimit, upperLimit);
    
    return 0;
}



/**
 * Prints all prime numbers between an interval defined by lower limit and upper
 * limit. 
 */
void printPrimes(int lowerLimit, int upperLimit)
{
    printf("All prime number between %d to %d are: ", lowerLimit, upperLimit);
    
    while(lowerLimit <= upperLimit)
    {
        //Checks whether the current number is prime or not.
        if(isPrime(lowerLimit))
        {
            printf("%d, ", lowerLimit);
        }
        
        lowerLimit++;
    }
}



/** 
 * Checks whether a number is prime or not. Returns 1 if the number is prime  
 * otherwise returns 0. 
 */  
int isPrime(int num)   
{  
    int i;  
      
    for(i=2; i<=num/2; i++)    
    {    
        /*   
         * If the number is divisible by any number   
         * other than 1 and self then it is not prime  
         */    
        if(num%i == 0)    
        {  
            return 0;  
        }    
    }   
      
    return 1;   
} 


Output
Enter the lower and upper limit to list primes: 10 50
All prime number between 10 to 50 are: 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47,

Happy coding ;)


Any doubt or suggestion write here. I will try my best to help. Before posting your code you must escape it to view. To format your source code and use format highlighting, post your source code inside
< code >< pre > -- Your source code -- < /pre >< /code > (Remove spaces from pre and code tags).

No comments:

Post a Comment