Write C++ program to find prime numbers in given range using functions

Introduction

I have used CodeBlocks compiler for debugging purpose. But you can use any C++ programming language compiler as per your availability.

#include <iostream>
using namespace std;
 
 
// Function declarations
int isPrime(int num);
void printPrimes(int lower, int upper);
 
int main()
{
    int lower, upper;
 
    cout<<"Enter the lower and upper limit to list primes: ";
    cin>>lower;
    cin>>upper;
 
    // Calling function to print all primes between the given range.
    printPrimes(lower, upper);
    return 0;
}
 
 
 
// Print all prime numbers between lower limit and upper limit.
 
void printPrimes(int lower, int upper)
{
    cout<<"List of prime numbers between "<<lower <<" and "<<upper <<" are: "<<endl;
 
    while(lower <= upper)
    {
        // Printing if current number is prime
        if(isPrime(lower))
        {
           cout<<lower<<endl;
        }
 
        lower++;
    }
}
 
//Checking whether a number is prime or not
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;
}

Result

Write C++ program to find prime numbers in given range using functions
Write C++ program to find prime numbers in given range using functions

Leave a Comment

x