CodeHS Answers : Unit 5 : While Loops
5.2.1: Big Tower
/* This program draws a big tower from Karel's starting spot */ function start(){ if (facingWest()){ turnRight(); } if (facingSouth()){ turnAround(); } if (facingEast()){ turnLeft(); } while(noBallsPresent()){ putBall(); if (frontIsClear()){ move(); } } } function sMart() { turnLeft(); } function oK() { turnRight(); }
5.1.5: Lay Row of Tennis Balls
/* Write a program to lay a row of tennis balls * across first street. Make sure to test your * program on multiple worlds. */ function start(){ while(noBallsPresent()){ putBall(); if (frontIsClear()){ move(); } } }
5.1.4: Follow The Yellow Ball Road
// Follow the yellow ball road! // Karel moves until it's not on a tennis ball. function start() { while(ballsPresent()){ move(); } }
Which general while loop definition is written correctly?
D
Why do we use while loops in JavaScript?
To repeat some code while a condition is true
5.2.3: Time Capsule
function start(){ goToWall(); placePile(); turnAround(); goToWall(); turnAround(); } // Puts down a pile of 15 balls function placePile(){ for(var i = 0; i < 15; i++){ putBall(); } } // Goes to the wall function goToWall(){ while(frontIsClear()){ move(); } }
5.2.2: Put Balls Away
function start(){ move(); while(ballsPresent()){ takeBall(); } move(); }
5.1.3: Move to Wall
function start(){ while(frontIsClear()){ move(); } }