Group
Functions in C++
Objective
1. Create a function that receives an integer and returns a boolean value indicating whether it is a prime number.
2. A number is prime if it is greater than 1 and divisible only by 1 and itself.
3. Use a loop to test divisibility from 2 up to the square root of the number.
4. In the main function, prompt the user for a number and call the function to check if it is prime.
5. Display the appropriate message based on the function's result.
Implement a function that returns whether a number is prime.
Example C++ Exercise
Show C++ Code
#include <iostream> // Include the iostream library for input and output
#include <cmath> // Include cmath for using the square root function
using namespace std; // Use the standard namespace
// Function to check if a number is prime
bool isPrime(int number) {
// Prime numbers must be greater than 1
if (number <= 1) {
return false; // Numbers less than or equal to 1 are not prime
}
// Check divisibility from 2 up to the square root of the number
for (int i = 2; i <= sqrt(number); i++) {
if (number % i == 0) {
return false; // If divisible by any number, it's not prime
}
}
return true; // If not divisible by any number, it's prime
}
// Main function - starting point of the program
int main() {
int num; // Variable to store the user's number
// Prompt the user to enter a number
cout << "Enter a number: ";
cin >> num; // Read the input number
// Call the isPrime function and display the result
if (isPrime(num)) {
cout << num << " is a prime number." << endl;
} else {
cout << num << " is not a prime number." << endl;
}
return 0; // End of the program
}
Output
Enter a number: 7
7 is a prime number.
Enter a number: 12
12 is not a prime number.