Advertisement

C++ Program to check a number is prime or not using class and object


In this program, You will learn how to check a number is prime or not using class and object in C++.


class Test{
    //statement
};
int main(){
   //statement
}

Example: How to check a number is prime or not using class and object in C++

#include<iostream>
using namespace std;

class Test {
public:

    int check(int x) {
        int i, p = 0;

        for (i = 2; i < x; i++) {
            if (x % i == 0) {
                p = 1;
                break;
            }
        }
        return p;
    }
};

int main() {

    int x, p;

    cout << "Enter a number:";
    cin >> x;

    Test obj;
    p = obj.check(x);

    if (p == 0) {
        cout << "Number is prime:" << x;
    } else {
        cout << "Number is not prime:" << x;
    }

    return 0;
}

Output:

Enter a number:17
Number is prime:17