In this post, you will learn how to Check Whether a Number is Prime or Not using C++ programming language.
This lesson will teach you how to check if a number is Prime or Not, with a for loop, assignment operator and decision making statement using the C++ Language. Let’s look at the below source code.
How to Check Whether a Number is Prime or Not?
RUN CODE SNIPPETSource Code
#include <iostream> using namespace std; int main() { int n, i, num = 0; cin>>n; cout<<"Enter a positive number: "<<n<<endl; for(i=2; i<=n/2; ++i) { if(n%i==0) { num=1; break; } } if (num == 0) cout<<"\n"<<n<<" is a prime number"; else cout<<"\n"<<n<<" is not a prime number"; return 0; }
Input
13
Output
Enter a positive number: 13 13 is a prime number
The statements #include<iostream>, using namespace std, int main are the main factors that support the function of the source code. Now we can look into the working and layout of the code’s function.
- A Prime Number is a number that is divisible only by itself and 1 (e.g. 2, 3, 5, 7, 11).
- Declare the variables n, i, num as integers and initialize the value of num as 0.
- Collect the positive number from the user and store it in the n using function
cin>>
and display the value usingcout<<
and the Insertion Operators'<<‘ , ‘>>’. - Create a for loop with the following condition
for(i=2; i<=n/2; ++i)
then create the loop statement. - The loop statement has an if statement where we find an compare the reminder of n and i with 0, if the condition is true then then the loop statement is executed.
- The loop statement has an assignment operator function to assign the value 1 to num and the
break;
statement stops or breaks the function. - After the for loop is executed the using decision making statement create a condition to check if the value of num is equal to 0.
- According to whether the condition is verified or not the respective output statement is displayed and the execution is terminated.
Note: The ‘ << endl ‘ in the code is used to end the current line and move to the next line and ‘\n’ is also a new line function, to understand how both the functions work exclude it from the code, move it around and work with it.