0% found this document useful (0 votes)
283 views1 page

C++ Program For Prime Numbers

This C++ program uses a function called isPrime to check if a positive integer input by the user is a prime number. The isPrime function uses a for loop to check if the input number is evenly divisible by any integer between 2 and half its value, returning false if so or true if it is only divisible by 1 and itself. The main function gets user input, calls isPrime, and prints whether the number is or isn't prime.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
283 views1 page

C++ Program For Prime Numbers

This C++ program uses a function called isPrime to check if a positive integer input by the user is a prime number. The isPrime function uses a for loop to check if the input number is evenly divisible by any integer between 2 and half its value, returning false if so or true if it is only divisible by 1 and itself. The main function gets user input, calls isPrime, and prints whether the number is or isn't prime.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

C++ Program for Prime numbers

#include <iostream>
using namespace std;

bool isPrime(int n) {
if (n <= 1) {
return false;
}
for (int i = 2; i <= n/2; i++) {
if (n % i == 0) {
return false;
}
}
return true;
}

int main() {
int num;
cout << "Enter a positive integer: ";
cin >> num;

if (isPrime(num)) {
cout << num << " is a prime number." << endl;
} else {
cout << num << " is not a prime number." << endl;
}

return 0;
}

You might also like