Solution for Exercise 16-8

ex1608

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

#define SIZE 5

struct bot {
    int xpos;
    int ypos;
};

struct bot initialize(struct bot b);

int main()
{
    struct bot robots[SIZE];
    int x;

    srand((unsigned)time(NULL));

    for(x=0;x<SIZE;x++)
    {
        robots[x] = initialize(robots[x]);
        printf("Robot %d: Coordinates: %d,%d\n",
                x+1,robots[x].xpos,robots[x].ypos);
    }
    return(0);
}

struct bot initialize(struct bot b)
{
    int x,y;

    x = rand();
    y = rand();
    x%=20;
    y%=20;
    b.xpos = x;
    b.ypos = y;
    return(b);
}

Notes

* See the typecast at Line 19?

* By creating the structure globally, you can code functions that are of that structure's type, such as the initialize() function at Line 30. In fact, that's the only way you can code a function that returns a structure.

* For a function to return a structure, the function must be declared of that structure type, as is done in Line 30.

* Structures are one method by which a function can "return" multiple values.

* In the book (first printing), the srandom() and random() functions are used intead of srand() and rand(), respectively. These functions are not available in all C language libraries, which is why I've changed them here.