C++ Program to check number is prime or not using constructor


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


Some list of prime number is : 2, 3, 5, 7, 11, 13, 17

Example: How to check number is prime or not using a constructor in C++.

#include<iostream>
using namespace std;

class Test {
public:

    int x;

    Test() {
        cout << "Enter a number:";
        cin >> x;
    }

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

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

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

};

int main() {

    Test obj;
    obj.check();

    return 0;
}

Output:

Enter a number:17
Number is prime:17