0% found this document useful (0 votes)
5 views2 pages

18

The document provides a C++ code snippet that checks if a number is prime. It includes a function 'check()' to verify if the number is positive, prompting the user to enter a positive number if it is negative. If the number is positive, it calls the 'prime()' function to determine if the number is prime and outputs the result accordingly.

Uploaded by

ultronverse01
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views2 pages

18

The document provides a C++ code snippet that checks if a number is prime. It includes a function 'check()' to verify if the number is positive, prompting the user to enter a positive number if it is negative. If the number is positive, it calls the 'prime()' function to determine if the number is prime and outputs the result accordingly.

Uploaded by

ultronverse01
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

18.

>Prime Numbers with a Twist


Ques. Write a code to check whether no is prime or not. Condition use function
check() to find whether entered no is positive or negative ,if negative then enter
the no, And if yes pas no as a parameter to prime() and check whether no is prime
or not?

Whether the number is positive or not, if it is negative then print the message
“please enter the positive number”
It is positive then call the function prime and check whether the take positive
number is prime or not.

Ans =

#include <iostream>
using namespace std;

bool check(int n) {
if (n < 0) {
cout << "Please enter a positive number.\n";
return false;
}
return true;
}

bool prime(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 n;
cout << "Enter a number: ";
cin >> n;

if (!check(n)) {
return 0;
}

if (prime(n)) {
cout << n << " is a prime number.\n";
} else {
cout << n << " is not a prime number.\n";
}

return 0;
}

You might also like