1. Writing functions that return values
  2. Braitenberg Exercise

Writing functions that return values

You have written many of your own functions by now. These functions have made the robot move forward or backward; to the left or right; etc. What if we want the job of our function to be the computation of a value -- for example, an average. In this case, we need to do two important things. We need the function to return the computed value, and we need to specify the type of value that the function will compute, as in:
int average(int value1, int value2) {
    return (value1 + value2)/2;
Notice here that the magic word "void" no longer appears at the beginning of our function header. Instead, we have replaced it with int, to indicate that this function is computing an integer value. ("void" means that the purpose of the function is to perform some action, rather than to compute some value.)

We can use this function by specifying its name in the context in which we want its value to be computed:

/* Andrea Danyluk */
/* October 2008 */

/* Program to illustrate if-else and while */
/* Goes forward computing average light */
/* Records min and max average light as it moves along */
/* Does this as long as stop button not pressed and neither touch
sensor detects a collision */

int LEFT_MOTOR = 3;     /* the left motor */
int RIGHT_MOTOR = 1;    /* the right motor */
int LEFT_TOUCH = 14;    /* the left touch sensor */
int RIGHT_TOUCH = 11;   /* the right touch sensor */

int RIGHT_LIGHT = 3;    /* the right light sensor */
int LEFT_LIGHT = 5;     /* the left light sensor */

void main() {
    int min_so_far = 255;
    int max_so_far = 0;
    while(!stop_button() && !digital(LEFT_TOUCH) && !digital(RIGHT_TOUCH)) {
        /* compute and remember the average light value */
        int average_light = average(analog(LEFT_LIGHT), analog(RIGHT_LIGHT));
        if (average_light < min_so_far) {
            min_so_far = average_light; 
        if (average_light > max_so_far) {
            max_so_far = average_light;  
        printf("Min = %d Max = %d\n", min_so_far, max_so_far);

/* go forward at full power */
void forward( ) {

int average(int value1, int value2) {
    return (value1 + value2)/2;

Braitenberg Exercise