//* Usefullness of enumeration *

#include <stdio.h> #include <string.h> typedef enum direction {NORTH, EAST, SOUTH, WEST, NA} direction ; // can be partially replaced by const int definitions: // const int NORTH =0, EAST =1, SOUTH =2, WEST =3, NA =4; // The function str_to_dir converts a string of characters to direction void str_to_dir(const char name[], direction *D) { if (strcmp(name,"north")==0) *D=NORTH; else if (strcmp(name,"n")==0) *D=NORTH; else if (strcmp(name,"east")==0) *D=EAST; else if (strcmp(name,"e")==0) *D=EAST; else if (strcmp(name,"south")==0) *D=SOUTH; else if (strcmp(name,"s")==0) *D=SOUTH; else if (strcmp(name,"west")==0) *D=WEST; else if (strcmp(name,"w")==0) *D=WEST; else *D=NA; } // The functions turnLeft and turnRight are examples of successor and predecessor functions void turnRight(direction D, direction *newD) { if (D==NORTH) *newD=EAST; else if (D==EAST) *newD=SOUTH; else if (D==SOUTH) *newD=WEST; else if (D==WEST) *newD=NORTH; else *newD=NA; } void turnLeft(direction D, direction *newD) { if (D==NORTH) *newD=WEST; else if (D==EAST) *newD=NORTH; else if (D==SOUTH) *newD=EAST; else if (D==WEST) *newD=SOUTH; else *newD=NA; } // The function updatePosition updates the postion of the manipulator within limits void updatePosition(direction D, int *x, int *y) { const int borderX=10, borderY=10; if (D==NORTH && *y<borderY) (*y)++; else if (D==EAST && *x<borderX) (*x)++; else if (D==SOUTH && *y>-borderY) (*y)--; else if (D==WEST && *x>-borderX) (*x)--; // else ; // noting } int main() { int x=0, y=0; for (;;) { char command[80]; direction D; do { printf("(%4d,%4d) > ", x, y); scanf("%s", &command); } while ( strlen(command)==0); str_to_dir(command, &D); if (D==NA) break; updatePosition(D, &x, &y); } return 0; }