What are and How to use Functions

So, you want to know what a function is in the context of programming? A function is a block of code that is given a name, some data to work on, a return value, and type. Functions are used by “calling” the name of the function and the specific parameters in the version you wish to use, when we say “call” we mean that you are writing the name of the function with all the parameters you wish to use. This aspect is important to remember as in some languages, you are allowed to name multiple functions the same word and the compiler then differentiates them by their parameters and their class relations.

Example and Description of a Function

 I will provide an example of a C function that performs the following math function: f(x)=a*cosh⁡(x/a). This is the equation of a catenary curve, “a” represents the flatness or steepness of the catenary and is constant, and the cosh is hyperbolic cosine. It takes a number x and returns a number f(x). To relate this further, everything to the right of the equals is in the function body, the x in f(x) is the parameter of the function, and the letter f is the name of the function.

We will work our way inside out. First, to calculate x/a in the cosh function, we will calculate this and store it in a new, temporary variable. We need to use cosh, so we will use an external library called math.h. We will next plug in the previously calculated value for x/a; then we will set this calculated cosh value to a new variable. Finally, we will multiply the stored cosh to get our final value.

Catenary Function in C
#include <math.h>

int main(){
    double x = 0.0;
//this will be our real value on the x-axis

    double a = 0.0;
//this will be a user set constant

    double y = 0.0;
//this is the function output

    //user sets a with some desired number
    //user also gives x
    y = catenary(a, x);
    return 0;
}
double catenary(double a, double x){
    double temp = 0.0;
    temp = x / a;
    temp = cosh(temp);
    return temp = a * temp;
}

Making a computer do things is easy; even more so when the task is as simple as computing math functions, however its much harder to ensure that a computer can take human input without crashing. Humans don’t always read instructions carefully, they may type an address into the box meant for their email, or worse yet, they may make a small typo in their address; the question then becomes how do we catch these types of errors and correct them? All these topics will be in my next post in the Fundamentals Series, so stay tuned for that! Have a most excellent day, wherever you are.

Leave a Reply

Your email address will not be published. Required fields are marked *