Add the public functions turnLeft, turnRight, and moveForward. The functions sho
ID: 3731676 • Letter: A
Question
Add the public functions turnLeft, turnRight, and moveForward. The functions should update the robot's x, y, and heading attributes and should not return anything. turnLeft and turnRight should update the robot's heading. If the robot's heading is 'N', turnLeft should result in the new heading being 'W moveForward should update the robot's x or y position by 1. If the robot's heading is 'N', moveForward should result in the y position increasing by one. If the robot's heading is 'S, moveForward should result in the y position decreasing by one.Explanation / Answer
class Robot
{
int x;
int y;
char heading;
public:
Robot(int start_x, int start_y, char start_heading)
{
x = start_x;
y = start_y;
heading = start_heading;
}
void turnLeft()
{
// if robot is currently moving north
if( heading == 'N' )
heading = 'W';
// if robot is currently moving south
else if( heading == 'S' )
heading = 'E';
// if robot is currently moving east
else if( heading == 'E' )
heading = 'N';
// if robot is currently moving west
else if( heading == 'W' )
heading = 'S';
}
void turnRight()
{
// if robot is currently moving north
if( heading == 'N' )
heading = 'E';
// if robot is currently moving south
else if( heading == 'S' )
heading = 'W';
// if robot is currently moving east
else if( heading == 'E' )
heading = 'S';
// if robot is currently moving west
else if( heading == 'W' )
heading = 'N';
}
void moveForward()
{
// if robot is currently moving north
if( heading == 'N' )
y++;
// if robot is currently moving south
else if( heading == 'S' )
y--;
// if robot is currently moving east
if( heading == 'E' )
x++;
// if robot is currently moving west
if( heading == 'W' )
x--;
}
};
int main()
{
Robot robot1 = Robot(9, 1, 'N');
robot1.moveForward();
robot1.turnLeft();
robot1.turnRight();
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.