Computer Science, asked by kulvinderkaur, 1 year ago

c++ to print the prime number between 100-200​

Answers

Answered by QGP
0

Primes in a Range - C++

We will use a bool function to check if a given number num is prime or not. We would check divisibility of num by every number from 2 to sqrt(num).

If divisibility is found, number is not prime and so return false. If no divisibility is found in the entire range, number is prime and so return true.

Now, begin the main() function and start a loop running from 100 till 200. Invoke the function to check if the number is prime, and if it is, print it to the screen.

Here goes the code.

 \rule{320}{1}

#include <iostream>

#include <cmath>      //Including for sqrt() function

using namespace std;

bool isPrime(int num)  //Function to check if a given number is Prime

{

   //We check divisibility of num by all numbers from 2 to sqrt(num)

   //If divisibility is found, number is not Prime, so return false

   for(int i=2;i<=(int)sqrt(num);i++)

   {

       if(num % i == 0)

       {

           return false;

       }

   }

   //If no divisibility is found, return true

   return true;

}

int main()

{

   int lowerlimit = 100;      //Setting Lower Limit to 100

   int upperlimit = 200;     //Setting Upper Limit to 200

   cout << "Primes between " << lowerlimit << " and " << upperlimit << " are:" << endl;

   

   for(int i = lowerlimit; i < upperlimit; i++)

   {

       if(isPrime(i))      //Calling Prime Checking Function

       {

           cout << i << endl;  //Printing Primes

       }

   }

   return 0;

}

Attachments:
Similar questions