Write a C++ program to accept a number and test whether it is a Prime number.
Write a C++ program to accept a number and test whether it is a
Prime number.
Write a C++ program to accept a number and test whether it is a
Prime number.
Best answer
In question it is mentioned that we are going to take input hence we will use cin variable
after that we have to check the entered number is prime or not therefore we know that 2 is a prime number and the numbers which are not divided by any other number except 1 is prime
We will create a loop using for loop to check the number divisibility by previous all number using i++
for (i = 1; i <= number; i++){
if (number % i == 0)
{
c++;
} }complete code ::
#include <iostream>
using namespace std;
int main()
{
int number, i, c = 0;
cout << "Enter any number number: "; cin>>number;
for (i = 1; i <= number; i++)
{
if (number % i == 0)
{
c++;
}
}
if (c == 2)
{
cout <<number<<"- is a Prime number" << endl;
}
else
{
cout <<number<<" - is not a Prime number" << endl;
}
return 0;
}
First declare header tags iostream
we used int main as we are doing operations with integers , initialize values and variables
Log in or create a free account to answer this question.