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