15. Program that inputs an integer and displays whether it is a prime number or not.

Chapter 6: 

Looping Structures

Programming Exercise

Problem # 15:

Write a program that inputs an integer and displays whether it is a prime number or not.

Solution:

#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
    int c, n, p;
    cout<<"Enter a number: ";
    cin>>n;
    if(n>1)  
        p=1;
    else
        p=0;
    for(c=2;c<n;c++)
    {
        if(n%c==0)
        {
            p=0;
            break;
        }
    }
    if(p==1)
    cout<<endl<<n<<" is a prime number.";
    else
    cout<<endl<<n<<" is a composite number.";  
    return 0;
}

Let me know in the comment section if you have any question.

Previous Post:
14. Program that inputs a number from the user and displays its factorial. It asks the user whether he wants to calculate another factorial or not.

Comments