c > functions > functions part 2

Functions Part 2

We continue by learning about functions with return values and those with both return values and arguments.

Functions with return values but no arguments

Here is a function that is used to get the current time:


#include <stdio.h>
#include <time.h>

char* get_current_time(){
    time_t t;
    time(&t);
    return ctime(&t);
}

int main(){
    printf("The current time is %s\n",get_current_time());
    return 0;
}

↗ Open 📋 Copy c/functions/current_time.c

The function doesn't accept any values but it does return a string. char* is just a way to indicate that the function returns a string. The current time is the string being returned.

Functions with both arguments and return values

When we use functions in Algebra we have an input ($x$) and a return value ($y$). This can be achieved in C:


#include <stdio.h>

double f(int x){
    double y = x*x+5*x+6;
    return y;
}

int main(){
    for (int x=0;x<10;x++){
        double y = f(x);
        printf("(%d,%g)\n",x,y);
    }
    return 0;
}

↗ Open 📋 Copy c/functions/f_of_x.c

The return value of a function takes the place of the function when the function passes the execution back to the main() function (or whichever function called it). Thus in this example, the code f(x) is replaced by the value of f(x) and this is stored as y in the loop;

Here is an example of a function that returns the larger of two integers:


#include <stdio.h>

int greater_of(int x, int y){
    if (x>y){
        return x;
    }
    return y;
}

int main(){
    int a=3,b=17;
    printf("The greater of %d and %d is %d\n",a,b,greater_of(a,b));
    return 0;
}

↗ Open 📋 Copy c/functions/greater_of.c