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
- Pass-by-Value: The
isPrimefunction receives a copy ofnumber. It performs the prime-checking logic on this copy. The original variable inmainremains unaffected by changes withinisPrime. - Pass-by-Reference: The
isPrimefunction receives a reference tonumber. Although the logic is the same as in the pass-by-value version, here it operates directly on the original variable. Any changes tonumwithinisPrimewould reflect inmain, but in this case, there are no modifications tonum.
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.