Home »
C++ Programs
C++ program to check whether the number is prime or not using class
Submitted by Shubh Pachori, on September 12, 2022
Problem statement
Given an integer number, we have to check whether it is prime or not using the class and object approach.
Example:
Input:
Enter Number : 19
Output:
19 is Prime.
C++ code to check whether the number is prime or not using the class and object approach
#include <iostream>
using namespace std;
// create a class
class IsPrime {
// private data members
private:
int number;
// a public function with a
// int type parameter
public:
// getNumber() function to insert
// the number
void getNumber() {
cout << "Enter Number : ";
cin >> number;
}
// isprime() function to check if the
// number is prime or not
void isprime() {
// initilaize two int type variable
int index, check = 0;
// for loop to check whether the number
// is prime or not
for (index = 2; index < number; index++) {
// if condition to check if the number is
// divisible by the index
if (number % index == 0) {
// print not prime if condition satisfied
cout << number << " is not Prime." << endl;
// increases check counter
check++;
// break to end the loop
break;
}
}
// if condition to check counter if
// count = 0 then it will print prime
if (check == 0) {
cout << number << " is Prime." << endl;
}
}
};
int main() {
// create an object
IsPrime P;
// calling getNumber() function to
// insert the number
P.getNumber();
// calling isprime() function to check if
// the number is prime or not
P.isprime();
return 0;
}
Output
RUN 1:
Enter Number : 23
23 is Prime.
RUN 2:
Enter Number : 119
119 is not Prime.
Explanation
In the above code, we have created a class IsPrime, one int type data member number to store the number, and public member functions getNumber() and isprime() to store the number and to check if the number entered is prime or not.
In the main() function, we are creating an object P of class IsPrime, inputting the number by the user using the getNumber() function, and finally calling the isprime() member function to check if the number entered is prime or not. The isprime() function contains the logic to check if the number entered is prime or not.
C++ Class and Object Programs (Set 2) »