Check if a Number is Prime Using a Function in C++

This C++ exercise focuses on the concept of creating reusable functions and applying mathematical logic to solve real-world problems. The task is to implement a function that checks whether a given number is a prime number or not. A prime number is a number greater than 1 that has no divisors other than 1 and itself.

By completing this task, you will practice writing and calling functions, using loops and conditionals, and applying modular arithmetic. This is a fundamental exercise for anyone learning how to work with number theory and control structures in C++.

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

 Copy 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.

Share this C++ Exercise


More C++ Programming Exercises of Functions in C++

Explore our set of C++ Programming Exercises! Specifically designed for beginners, these exercises will help you develop a solid understanding of the basics of C++. From variables and data types to control structures and simple functions, each exercise is crafted to challenge you incrementally as you build confidence in coding in C++.