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


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


techstudy.org

HP 15 Core i3 7th gen Laptop(4GB, 1TB HDD, Windows 10) | Rs. 31,490

Introduction

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


  1. #include <iostream>
  2. using namespace std;
  3.  
  4.  
  5. // Function declarations
  6. int isPrime(int num);
  7. void printPrimes(int lower, int upper);
  8.  
  9. int main()
  10. {
  11. int lower, upper;
  12.  
  13. cout<<"Enter the lower and upper limit to list primes: ";
  14. cin>>lower;
  15. cin>>upper;
  16.  
  17. // Calling function to print all primes between the given range.
  18. printPrimes(lower, upper);
  19. return 0;
  20. }
  21.  
  22.  
  23.  
  24. // Print all prime numbers between lower limit and upper limit.
  25.  
  26. void printPrimes(int lower, int upper)
  27. {
  28. cout<<"List of prime numbers between "<<lower <<" and "<<upper <<" are: "<<endl;
  29.  
  30. while(lower <= upper)
  31. {
  32. // Printing if current number is prime
  33. if(isPrime(lower))
  34. {
  35. cout<<lower<<endl;
  36. }
  37.  
  38. lower++;
  39. }
  40. }
  41.  
  42. //Checking whether a number is prime or not
  43. int isPrime(int num)
  44. {
  45. int i;
  46.  
  47. for(i=2; i<=num/2; i++)
  48. {
  49. /*
  50.   If the number is divisible by any number
  51.   other than 1 and self then it is not prime
  52.   */
  53. if(num % i == 0)
  54. {
  55. return 0;
  56. }
  57. }
  58.  
  59. return 1;
  60. }
  61.  

Result

C++ language techstudy.org

     





Related Topics




Popular Posts