C Programming: You are going to write an API for controlling an ant that lives i
ID: 3844934 • Letter: C
Question
C Programming:
You are going to write an API for controlling an ant that lives in one-dimensional space! This API will be contained in two files ant.c and ant.h. The contents of ant.h is given below:
#ifndef _ant_h_
#define _ant_h_
struct ant {
int position;
int direction;
};
void init_ant (struct ant* a, int position);
void ant_turn (struct ant* a);
void ant_move (struct ant* a, unsigned int distance);
int ant_get_position (struct ant* a);
char* ant_get_direction (struct ant* a);
#endif /* _ant_h_ */
Your job is to write the file ant.c. Test your implementation using the following code test.c:
#include <stdio.h>
#include "ant.h"
void report (struct ant* a)
{
printf ("[Position: %i] ", ant_get_position(a));
printf ("[Direction: %s] ", ant_get_direction(a));
}
int main (int argc, char** argv)
{
struct ant bob;
init_ant (&bob, 10);
report (&bob);
ant_move (&bob, 5);
ant_move (&bob, 2);
report (&bob);
ant_turn (&bob);
ant_move (&bob, 20);
report (&bob);
}
Explanation / Answer
ant.c file
#include "ant.h"
void init_ant (struct ant *a, int position)
{
a->position = position;
}
void ant_turn (struct ant *a)
{
a->position = (a->position) - 40;
}
void ant_move (struct ant *a, unsigned int distance)
{
a->position = a->position + distance;
}
int ant_get_position (struct ant *a)
{
return a->position;
}
char* ant_get_direction (struct ant *a)
{
if((a->position) > 0)
return "right";
else
return "left";
}
Output:
[Position: 10] [Direction: right]
[Position: 17] [Direction: right]
[Position: -3] [Direction: left]
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.