Subroutines: procedures and functions - 2


function is a subroutine that returns a result (number, character line, etc.).

Imagine that you have ordered a product from an online store. From a programming point of view, you called some subroutine, and unlike a procedure, this subroutine must return a result - deliver the product you ordered. These subroutines are called functions.
A function is formatted in exactly the same way as a procedure. The only difference from a procedure is the presence of a special operator return,
 after which the value to be returned to the main program is written.

A function that returns the arithmetic mean of two integers would look like this:
float average(int a, int b)
{
    float avg = (a + b) / 2.0;
    return aug;
}
It remains to figure out how to call this function in the main program. You should not call a function in the same way as a procedure:
average(10, 5); 
The value returned by the function will be lost. It is as if the goods from the online store were not given to anyone, but thrown away. It is unlikely that the customer will like it.

It is more correct to store the result in a variable (or display it on the screen):
float a = average(10, 5); 
Console.WriteLine(average(10, 5));< /code>

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;
}