Repeat actions cleanly. Group code into reusable chunks.
for and while loops."Keep doing this as long as the condition is true."
while (Brain.timer(msec) < 3000) {
LeftMotor.spin(forward, 50, percent);
RightMotor.spin(forward, 50, percent);
wait(20, msec);
}
LeftMotor.stop();
RightMotor.stop();
"Do this a specific number of times."
for (int i = 0; i < 4; i++) {
// drive forward then turn 90°, repeats 4 times for a square
driveForward(12); // 12 inches (we'll write this function below)
turnRight(90);
}
Functions are reusable blocks. Write once, call anywhere.
// A function that turns the robot right by a given angle.
void turnRight(int degrees) {
LeftMotor.spinFor(forward, degrees, deg, false); // false = don't wait
RightMotor.spinFor(reverse, degrees, deg, true); // true = wait until done
}
int main() {
turnRight(90);
turnRight(45);
turnRight(180);
}
// Returns the average of two numbers
double average(double a, double b) {
return (a + b) / 2.0;
}
double avgEncoder = average(LeftMotor.position(deg), RightMotor.position(deg));
void means the function returns nothing.double here means the function returns a decimal number.Write a function driveDistance(int inches) that drives forward a given number of inches (you can convert inches to motor degrees using the wheel circumference, we'll do this properly in Week 6). Then use a for-loop to drive in a square: 4 sides of 24 inches with 90° turns.
Two programs with intentional errors. Spot the bug.
for (int i = 0; i <= 4; i++) {
driveInches(12);
turnRight(90);
}
int average(int a, int b) {
return (a + b) / 2;
}
int main() {
double result = average(7, 4);
Brain.Screen.print("avg = %.2f", result);
// prints 5.00 instead of 5.50
}