In this program we will check whether a number entered by the user is prime or not. A prime number is a number which can be divided only by 1 and itself. For example 5, 7, 13 and so on.
To understand this program, you must know the following topics in c++ :
- Conditional statements
- Loops
- Break and continue statement
Program
#include<iostream>
using namespace std;
int main()
{
int i, num, check=0;
cout<<"Enter the number";
cin>>num;
for(i = 2; i < num; i++)
{
if(num % i == 0)
{
check++;
break;
}
}
if(check == 0)
{
cout<<"The number is prime";
}
else
{
cout<<"The number is not prime";
}
return 0;
}
Output 1
Enter a positive number9
The number is not prime
Output 2
Enter a positive number13
The number is prime
Explanation:
- After including the standard library ‘iostream’ and mentioning the std namespace, we have declared three variables – num, i, and check and initialized the variable check with 0. The variable num will store the number entered by the user, i would be used to run the loop and check would be used to decide which message to display.
- After that we ask the user to enter a positive number by displaying a message with the cout statement. The number would get stored in the num variable using the cin statement.
- Next we have started a for loop that will run from 2 to the number that the user will enter. For example if the user enter 10, the loop will run from 2 to 10. Every time the loop runs, we are checking if the number is completely divisible by the current value of i or not. If it is divisible by any number in this range (2 – num), we can say the number is not prime. In this case the value of check is incremented and the loop will break.
- once the loop terminates we can now check for the value of the variable check. If its value is still 0 that means the condition inside the loop never became true, and the number is prime and if the value of check has incremented then the number is not prime.
- So lastly we have put if and else statements. If the value of check is equal to zero, the program will end up by displaying a message that says “The number is prime”, else the message “The number is not prime” will be displayed.