Close
Close

c++program to display prime number between two interval using function

   sahebalam , sagi rama krishna college


Answers

  •   

    I guess you are asking to print between two numbers (an interval). I have written a code for the same in which prime numbers between num1 and num2 are printed.

    #include <iostream> 
    using namespace std; 
    
    void primeNumbers (int low, int high) {   
       while (low <= high) {
          int flag = 0;
          for(int i = 2; i <= low/2; i++) {
             if(low % i == 0) {
                flag = 1;
                break;
             }
          }
          if (flag == 0)
             cout << low << " ";
          low++;
       }
    }
    
    int main() {
       int num1 = 40, num2 = 70;
       cout<<"Prime numbers between "<<num1<<" and "<<num2<<": ";
       primeNumbers(num1,num2);
       return 0;
    }
    

    In this code, the while loop is iterated till the value of num1 is less than that of num2. Inside the while loop, the value of a variable flag is set 0 and it is checked if num1 is a prime number. If num1 is not found to be a prime number, the flag value is set to 1 and num1 is not primted. Otherwise it is printed. 

    After that, the num1 value is incremented by 1 and the whole process is repeated till num1 is less than num2.



Ask Yours
Post Yours
Write your answer