In: Computer Science
I wrote a code snippet to draw a bit of 'abstract art':
yertle.penDown(); yertle.forward(10); yertle.right(Math.PI/2); yertle.forward(10); yertle.right(Math.PI/2); yertle.forward(10); yertle.right(Math.PI/2); yertle.forward(10); yertle.right(Math.PI/2); yertle.left(Math.PI/2); yertle.forward(20); yertle.right(Math.PI/2); yertle.forward(20); yertle.right(Math.PI/2); yertle.forward(20); yertle.right(Math.PI/2); yertle.forward(20); yertle.right(Math.PI/2); yertle.left(Math.PI/2); yertle.forward(30); yertle.right(Math.PI/2); yertle.forward(30); yertle.right(Math.PI/2); yertle.forward(30); yertle.right(Math.PI/2); yertle.forward(30); yertle.right(Math.PI/2); yertle.left(Math.PI/2); yertle.forward(40); yertle.right(Math.PI/2); yertle.forward(40); yertle.right(Math.PI/2); yertle.forward(40); yertle.right(Math.PI/2); yertle.forward(40); yertle.right(Math.PI/2); yertle.left(Math.PI/2); yertle.penUp();
My instructor suggested I could get the same result from a
much shorter program, but I don't see how.
What should I write instead?
(Keep it concise, and don't include anything outside the scope of
the question)
yes,
this seems a pretty long code. the thing you want to do can be done with much lesser steps.
i can see from the code that you are running similar lines of code many times.
like all your code is full of 'yertle.right(Math.PI/2);' and 'yertle.forward(i);'.
now you have done this 15-16 times. but suppose if we get a similar question where we need to do it a 1000 times. in that case we can't write these instructions a 1000 times manually. right?
for purposes like these we use the concept of 'loop'. loop is something which helps us to write multiple lines of code in just 3 lines.
this does nothing but saves our time.
just to give you an example,
see the following code
instead of writing the same stuff 4 times, what we can do is to run a loop.
we use 'for' function to run a loop.
in the above example, we need to run the loop 4 times. so we will use the 'for' loop as
more precisely, it can be written as:
for(int i = 0;i<4;i++)
{
yertle.forward(40);
yertle.right(PI/2);
}
this will work same as
so you see, we can save so much of time if we run a loop.
your instructor might be talking about this.
hope it helps