Check prime number using function in C++


This program checks if a given number is prime or not. It first takes input of the number to be checked from the user using the cin function. Then it calls the prime function, which takes the number as an argument.

The prime function initializes variables i, m, and flag to 0. m is the upper limit of the range of divisors to be checked. It then checks if the number is divisible by any number from 2 to m. If it is, then the function prints that the number is not prime and sets the flag variable to 1. If the number is not divisible by any number in this range, then it is prime, and the function prints that the number is prime. Finally, the main function returns 0 and the program ends.

Source Code

#include<iostream>
using namespace std;
void prime(int n)
{
    int i,m=0,flag=0;
    m=n/2;
    for(i=2;i<=m;i++)
    {
        if(n%i==0)
        {
            cout<<"Number is not Prime."<<endl;
            flag=1;
            break;
        }
    }
    if(flag==0)
        cout<<"Number is Prime."<<endl;
}
int main()
{
    int n;
    cout<<"Enter the Number to check Prime: ";
    cin>>n;
    prime(n);
    return 0;
}
To download raw file Click Here

Output

Enter the Number to check Prime: 10
Number is not Prime.

Program List


Flow Control

IF Statement Examples


Switch Case


Goto Statement


Break and Continue


While Loop


Do While Loop


For Loop


Friend Function in C++


String Examples


Array Examples


Structure Examples


Structure & Pointer Examples


Structure & Functions Examples


Enumeration Examples


Template Examples


Functions


Inheritance Examples

Hierarchical Inheritance


Hybrid Inheritance


Multilevel Inheritance


Multiple Inheritance


Single Level Inheritance


Class and Objects

Constructor Example


Destructor Example


Operator Overloading Example


Operator and Function Example


List of Programs


Pointer Examples


Memory Management Examples


Pointers and Arrays


Virtual Function Examples