question archive Use nested for-loops to have the turtle draw a snowflake of polygons
Subject:Computer SciencePrice:2.87 Bought7
Use nested for-loops to have the turtle draw a snowflake of polygons. Use the variable turnAmount to turn after each shape and the variable n for the sides of the polygon.
import java.util.*;
import java.awt.*;
public class TurtleSnowflakes
{
public static void main(String[] args)
{
World world = new World(300,300);
Turtle yertle = new Turtle(world);
yertle.setColor(Color.blue);
// Use this variable in the loops
int turnAmount = 30;
// 1. Write a for loop that runs many times
// 2. Change it to use turnAmount to figure out how many times to run
// 1 & 2. Write an inner loop that draws a triangle (3 sides, 120 degree turns)
// 3. Then change it to be any polygon with a variable n
// turn turnAmount degrees before drawing the polygon again
// 4. Add an if statement that changes the colors depending on the loop variables
world.show(true);
}
}
Answer:
import java.utils.*;
import java.awt.*;
public class Main {
public static void main(String[] args) {
World world = new World(300,300);
Turtle yertle = new Turtle(world);
yertle.setColor(Color.blue);
int turnAmount = 30;
int outerIteration = 360/turnAmount;
int n = 5; //no of sides for polygon
//(1)(2)
for(int i=1;i<=outerIteration;i++) {
//if statement for changing color of polygon (4)
if (i%2==1) {
yertle.setColor(Color.green);
}
else {
yertle.setColor(Color.blue);
}
// change value of n to 3 for changing polygon to triangle (3)(4)
for(int side=1;side<=n;side++) {
yertle.forward();
yertle.turn(360/n);
}
yertle.turn(turnAmount);
}
}
}