0 votes
213 views
in Programming by
edited
Write a C++ program to accept a number and test whether it is a

Prime number.

1 Answer

0 votes
by (98.9k points)
selected by
 
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 


by (98.9k points)
edited
consider sharing these answer with your friends and ask your doubts here !!!!!

Related questions

+1 vote
1 answer 248 views
0 votes
1 answer 161 views
0 votes
1 answer 230 views
+1 vote
1 answer 193 views

Doubtly is an online community for engineering students, offering:

  • Free viva questions PDFs
  • Previous year question papers (PYQs)
  • Academic doubt solutions
  • Expert-guided solutions

Get the pro version for free by logging in!

5.7k questions

5.1k answers

108 comments

559 users

...