Write a program which simulates the movement of a turtle as follows:
At the beginning, the turtle is at the origin, i.e. point (0,0). It is facing in the positive x direction. For the purpose of this exercise, let us assume that the coordinate axes are drawn as in mathematics, i.e. the x axis points in the East direction, and the y axis in the North direction.
The user can type commands to move the turtle. The commands are:
F : This causes the turtle to move 1 unit in the direction it
is currently facing.
L : This causes the turtle to turn left by 90 degrees.
E : This causes the program to print the current coordinates of
the turtle and stop execution.
You can assume that the user will not type any other letters besides the ones shown. Note that while there is no command to turn right, we can get the effect by using LLL, i.e. turning left thrice.
As an example, if the user input is "FFLLLFFLFE", then it will cause the turtle to move to (3,-2) and the program will print "3 -2" and stop.
The input and output is also shown in the test cases.
Answers
#include <iostream>
using namespace std;
int main()
{
int i, turn, x, y;
char ip[100];
turn = 0;
x = 0;
y = 0;
cout << "The Turtle has started its journey. He is currently at (0,0)" << endl;
cout << "The the inputs should be in Upper Case." << endl;
cin >> ip;
for (i=0; i>-1; i++)
{
if (ip[i] == 'F')
{
if (turn == 0)
{
x = x + 1;
}
else if (turn == 90)
{
y = y + 1;
}
else if (turn == 180)
{
x = x - 1;
}
else if (turn = 270)
{
y = y - 1;
}
else if (turn = 360)
{
turn = 0;
x = x + 1;
}
}
else if (ip[i] == 'L')
{
turn = turn + 90;
if (turn == 360)
{
turn = 0;
}
}
else if (ip[i] == 'E')
{
cout << "The turtle has stopped." << endl;
cout << "The coordinates are: " << "(" << x << "," << y << ")";
return 0 ;
}
}
}
Hope it helps :)