Site icon T4Tutorials.com

C++ Program to check whether a number is a prime or composite number.

Pass-by-Value

In the pass-by-value approach, the function receives a copy of the argument, and any changes made to the parameter inside the function do not affect the original argument.

#include <iostream>
using namespace std;

// Function to check if a number is prime or composite (pass-by-value)
bool isPrime(int num) {
    if (num <= 1) return false; // Numbers less than or equal to 1 are not prime
    for (int i = 2; i <= num / 2; ++i) {
        if (num % i == 0) return false; // Number is divisible by i, so it's not prime
    }
    return true; // Number is prime
}

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

Pass-by-Reference

In the pass-by-reference approach, the function receives a reference to the argument, allowing modifications to the argument inside the function to affect the original variable.

#include <iostream>
using namespace std;

// Function to check if a number is prime or composite (pass-by-reference)
bool isPrime(int& num) {
    if (num <= 1) return false; // Numbers less than or equal to 1 are not prime
    for (int i = 2; i <= num / 2; ++i) {
        if (num % i == 0) return false; // Number is divisible by i, so it's not prime
    }
    return true; // Number is prime
}

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

Explanation

Sample Output

Assuming you enter 7 as the number:

For Pass-by-Value:

Enter a number: 7
7 is a prime number.

For Pass-by-Reference:

Enter a number: 7
7 is a prime number.

 

Exit mobile version