C++ Program to Check Whether a Number is Prime or Not

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 SNIPPET

Source 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.

  1. Prime Number is a number that is divisible only by itself and 1 (e.g. 2, 3, 5, 7, 11).
  2. Declare the variables n, i, num as integers and initialize the value of num as 0.
  3. Collect the positive number from the user and store it in the n using function cin>>  and display the value using cout<< and the Insertion Operators'<<‘ , ‘>>’.
  4. Create a for loop with the following condition for(i=2; i<=n/2; ++i) then create the loop statement.
  5. 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.
  6. The loop statement has an assignment operator function to assign the value 1 to num and the break; statement stops or breaks the function.
  7. 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.
  8. 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.

Share:

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

In this post, you will learn how to Check Armstrong Number using C++ programming language. This lesson will teach you...
  • C++
  • December 2, 2024
In this post, you will learn how to Calculate the Sum of Natural Numbers using C++. This lesson will teach...
  • C++
  • December 2, 2024
In this post, you’ll learn how to write a Program to Add Two Integers in C++. This lesson will help...
  • C++
  • November 30, 2024