DEV Community

Madhuban Khatri
Madhuban Khatri

Posted on

Find Prime Number in C++

Hello friends, In this post I will show you how to make a program which is find a prime number using C++ language.

Code explaination

  • Create a void function 'isPrime' which is take two arguments 'n' and 'i'.
  • 'n' is a number and 'i' have the initial value of 2.
  • In this function, a while loop is running till 'i' is less than 'n'. In this loop.
  • In this loop, if n%i is equal to zero then 'n' is not a prime number. otherwise it is.
  • main function have four test cases to check the number is prime or not.
#include<iostream>
using namespace std;

void isPrime(int n, int i=2)
{
    while(i<n)
    {
        if (n%i==0)
        {
            cout<<n<<" is not a prime number"<<endl;
            break;
        }
        else
        {
            cout<<n<<" is a prime number"<<endl;
            break;
        }

        i++;
    }
}
int main(){
    // Test cases
    isPrime(17);
    isPrime(16);
    isPrime(23);
    isPrime(20);

    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Follow me on Github

Here you can find my projects which is very useful for you.

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more