Module: Subroutines: procedures and functions - 2


Problem

6/10

Boolean function

Theory Click to read/hide

Often, programmers use boolean functions that return boolean values ​​true or false (true or false).
Such functions are useful for checking a property.
Consider two examples of writing a logical function that checks a number for evenness

Best way:
expression result
n % 2 == 0
will be true (true) or false (false)
No need to write a conditional statement.
Don't do that.
Of course, you can do that, but this is a longer entry.
bool isEven(int n)
{
    return (n % 2 == 0);
}
bool isEven(int n)
{
    if (n % 2 == 0) {
        return true;
  }
    else {
        return False;
  }
}

And the last note about working with functions and procedures: the number of functions and procedures in the program is not limited. In addition, one subroutine can call another subroutine and even itself.
Also, after the program reaches the return in the function, the program immediately stops executing the function and returns the value.
That is, the second example from the table could also be shortened like this:
bool isEven(int n)
{
    if (n % 2 == 0) {
        return True
    }
    return False;
}

 

Problem

An integer is said to be prime if it is only divisible by 1 and itself. Write a boolean function (a function that returns true or false ) to determine if a given number is prime.
The main program uses the result of the logic function.
Example.
Input Output
4 NO
5 YES