i had to make a program that decides whether the integer the user entered is prime or not, then i had to make a function named isPrime to return 1 if it's prime and 0 if it's not prime. i made the program and it works, i sent it to my professor to look it over and he told me the function isPrime has to determine whether the integer is prime using two return statements, return 0 if not prime, 1 if prime. i used and if else chain in the return fuction, how do i do what my professor is talking about, cause is it returns 1 or 0, how would that make it display "prime' or "not prime". do i have to put the loop that determines if it's a prime number in the return function instead of main?
You could just drop a return in your if statement in the isPrime function and another in the else. I am not a fan of multiple returns in a function like that. You could just make the function a bool which returns true/false ... 1/0
1 2 3 4 5 6 7
bool isPrime(int p)
{
bool flag = false;
if (p == 2)
flag = true;
return flag;
}
LowestOne: i copied and pasted your program to c++ but when i compile i get two errors:
error 1 for line int p=0
"decleration of 'int p' shadows a parameter.
error 2 for line while(i <= abs(a))
"'a' was not declared in this scope
how do you make it so the user inputs something into the isPrime function instead of in main?
how do return functions work in the sense that if isPrime returns 1 it will diplay "prime" to the monitor and if isPrime returns 0 it displays "not prime" to the monitor because i though return just ends the function?
Yeah, I guess my hack and slash isn't copy/paste-able. I guess I'll leave it to you to figure those errors out.
You don't want to ask for the number from within the isPrime function. All the isPrime function should do is return 1 or 0 dependent upon whether the argument passed to it is prime. All functions should do one thing.
return returns that value back to wherever called the function:
1 2 3 4 5 6 7 8 9 10
int getNumber( void )
{
return 1234;
}
int main( void )
{
int number = getNumber();
cout << number; // prints 1234
}
So you need to do two things. First, move the lines 14-22 into the isPrime function ( and get it to work also ).
Then, instead of printing to the console in the if statement of isPrime, return the correct value;
1 2 3 4 5 6 7 8 9
int isPrime( int number )
{
// working lines 14-22
if ( p == 2 )
return 1;
elsereturn 0;
}
Now from within main, you can call it like so:
1 2 3 4 5 6 7 8 9
int number;
cin >> number;
int number_is_prime = isPrime( number );
if ( number_is_prime )
cout << number << " is prime\n";
else
cout << number << " is not prime\n";