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.

Top comments (0)