Skip to main content

Prime number program: procedural and OOP

Short answer

The procedural version uses a separate isPrime function checking divisibility up to sqrt(n). The OOP version wraps the number inside a class with private member n, and methods read(), isPrime(), display() to bind data and behavior securely.

Write a program to find prime number in procedural and object oriented ways.

A prime number is greater than 1 and divisible only by 1 and itself. To test n, check divisibility by every number from 2 to √n.

Procedural way

Data (n) and the function are separate; the number is passed to a function.

#include <iostream>
using namespace std;

int isPrime(int n) {
    if (n < 2) return 0;
    for (int i = 2; i * i <= n; i++)
        if (n % i == 0) return 0;
    return 1;
}

int main() {
    int n;
    cout << "Enter a number: ";
    cin >> n;
    if (isPrime(n)) cout << n << " is prime" << endl;
    else cout << n << " is not prime" << endl;
    return 0;
}

Object oriented way

The number and the function that tests it are bound together in a class.

#include <iostream>
using namespace std;

class Number {
    int n;                       // data hidden inside the class
public:
    void read() {
        cout << "Enter a number: ";
        cin >> n;
    }
    bool isPrime() {
        if (n < 2) return false;
        for (int i = 2; i * i <= n; i++)
            if (n % i == 0) return false;
        return true;
    }
    void display() {
        if (isPrime()) cout << n << " is prime" << endl;
        else cout << n << " is not prime" << endl;
    }
};

int main() {
    Number obj;
    obj.read();
    obj.display();
    return 0;
}

Sample output (both): for input 17, 17 is prime; for input 15, 15 is not prime.

Difference: in the procedural version n is a free variable passed around; in the OOP version n is private data of the object and only its member functions can use it.

✓ Answer checked by Claude Opus 5.5 (high effort)

All Object Oriented Programming chapter 1 questions →