Q:

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

0

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

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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:

Enter the lower and upper limit to list primes: 20

50

List of prime numbers between 20 and 50 are: 

23

29

31

37

41

43

47

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Write C++ program to find diameter, circumference ... >>
<< Write C++ program to print all strong numbers betw...