0 votes
211 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 245 views
0 votes
1 answer 156 views
0 votes
1 answer 223 views
+1 vote
1 answer 191 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

550 users

...