C++

A C++ Program To Determine Whether An Integer Input Is Prime Or Not

A prime number is one that can only be divided by one and itself. For instance, the number five is a prime number since it can only be divided by one and itself.
This software examines whether or not the value of num (input by user) is a prime integer.

Check to see if a number is a prime number, for instance.

You need be familiar with the C++ for loop, if-else, and break statements in order to comprehend this program.

#include <iostream>
using namespace std;
int main(){
   int num;
   bool flag = true;
   cout<<"Enter any number(should be positive integer): ";
   cin>>num;

   for(int i = 2; i <= num / 2; i++) {
      if(num % i == 0) {
         flag = false;
         break;
      }
   }
   if (flag==true)
      cout<<num<<" is a prime number";
   else
      cout<<num<<" is not a prime number";
   return 0;
}

Output:

Enter any number(should be positive integer): 149
149 is a prime number

Simply change the code in the application above with the following to solve this issue using a while loop:

for(int i = 2; i <= num / 2; i++) {
   if(num % i == 0) {
      flag = false;
      break;
   }
}

with this code:

int i=2;
while(i<=num/2){
   if(num % i == 0)
   {
      flag = false;
      break;
   }
   i++;
}

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button