Programming Examples

Cpp program to check whether it is a prime number or not using while loop


Write a cpp code to input a number and check whether it is a prime number or not.

#include<iosream>
using namespace std;
int main(){
     int num,count=0;
     cout<<"Enter any integer number:";
     cin>>num;
     int temp=num;
     while(num>0){
        if(temp%num==0){
             count+=1;
        }
        num--;
     }
     if(count==2){
        cout<<"It is a prime number";
     }
     else{
        cout<<"Not a prime number";
     }
     return 0;   
}
Method 2:
#include <iosream>
using namespace std;
int main() {
    int num;
    bool isPrime = true;
    cout << "Enter a positive integer: ";
    cin >> num;
    int i = 2;
    while (i <= num/2) {
        if (num % i == 0) {
            isPrime = false;
            break;
        }
        i++;
    }
    if (isPrime) {
        cout << num << " is a prime number" << endl;
    } else {
        cout << num << " is not a prime number" << endl;
    }
    return 0;
}
Note: while (i <= num/2)
This is because any factor of num greater than num/2 will result in a quotient that is less than 2. 
Therefore, we only need to check for factors up to num/2. For example, if num is 10, then the loop will run from i = 2 to i = 5 (inclusive), checking for factors of num between 2 and 5.
Output

Enter any integer number:10

Not a prime number

CCC Online Test 2021 CCC Practice Test Hindi Python Programming Tutorials Best Computer Training Institute in Prayagraj (Allahabad) Best Java Training Institute in Prayagraj (Allahabad) Best Python Training Institute in Prayagraj (Allahabad) O Level Online Test in Hindi Bank SSC Railway TET UPTET Question Bank career counselling in allahabad Sarkari Naukari Notification Best Website and Software Company in Allahabad Sarkari Exam Quiz