Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

How do I use a while loop to generate the simulation of a turtle who starts at p

ID: 3672549 • Letter: H

Question

How do I use a while loop to generate the simulation of a turtle who starts at position (100, 100) and is headed to the right? I am told that it can only move in a straight line to the right (+x), down (+y), left (-x) and up (-y). at every step the turtle will be told to move a certain number of steps or to turn 90 degrees. The turtle will have six steps in total, with every third and sixth move generating the direction and position of the turtle, as well as outputting the minimum and maximum x and y coordinates that the turtle moved at the end. I am just confused as to how to even start coding this program?

Explanation / Answer

#include<iostream>
#include <limits>

using namespace std;

char getDirection(char currentDirection){
   if(currentDirection == 'r')
       return 'd';
   else if(currentDirection == 'd)
       return 'l';
   else if(currentDirection == 'l')
       return 'u';
   else if(currentDirection == 'u')
       return 'r';
}
int getNewX(int x,char direction){
   if(direction == 'r')
       return x + 1;
   else if (direction == 'l')
       return x - 1;
   else
       return x;
}
int getNewY(int y,char direction){
   if(direction == 'u')
       return y + 1;
   else if (direction == 'd')
       return y - 1;
   else
       return y;
}

int main(){
   char direction = 'r'; //direction can be l,r,u,d,turn
   string command = 'move'; //move or turn
   int x,y; //turtle starting position
   int minX,minY,maxX,maxY;
   int steps = 0;
   minX = minY = INT_MAX;
   maxX = maxY = INT_MIN;
   while(steps < 6){
       cout<<"Move or turn?"<<endl;
       cin>>command;
       switch(command){
           case turn:
               direction = getDirection(direction);
               break;
           case move:
               x = getNewX(x,direction);
               y = getNewY(y,direction);
               if(x > maxX)
                   maxX = x;
               if(x < minX)
                   minX = x;
               if(y > maxY)
                   maxY = y;
               if(y < minY)
                   minY = y;
                   steps++;
               break;
       }
       if(steps % 3 == 0){
                   cout<<"Min and max X are"<<minX<<", "<<maxX;
                   cout<<"Min and max Y are"<<minY<<", "<<maxY;
                   //reset min and max
                   minX = minY = INT_MAX;
                   maxX = maxY = INT_MIN;
               }
   }

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote